有人可以在这里把我引向正确的方向吗,因为我完全困惑为什么当我从我的 ViewModel 调用 GetGeopositionAsync 时,它挂起但是当从我的视图中调用它时它工作正常?
这是有效的代码:
private async void btnLocate_Click(object sender, RoutedEventArgs e)
{
if (this._geolocator.LocationStatus != PositionStatus.Disabled && this._geolocator.LocationStatus != PositionStatus.NotAvailable)
{
try
{
this._geolocator.DesiredAccuracyInMeters = 5;
Geoposition position = await this._geolocator.GetGeopositionAsync();
Geocoordinate geocoordinate = position.Coordinate;
this.mapWithMyLocation.Center = CoordinateConverter.ConvertGeocoordinate(geocoordinate);
}
catch (System.UnauthorizedAccessException)
{
throw;
}
catch (TaskCanceledException)
{
throw;
}
catch (Exception)
{
throw;
}
}
}
这是不起作用的代码:
public class LocationEntryViewModel : BaseViewModel
{
async public Task<GeoCoordinate> GetMyLocation()
{
if (this._geolocator.LocationStatus != PositionStatus.Disabled && this._geolocator.LocationStatus != PositionStatus.NotAvailable)
{
try
{
this._geolocator.DesiredAccuracyInMeters = 5;
Geoposition position = await this._geolocator.GetGeopositionAsync();
Geocoordinate geocoordinate = position.Coordinate;
return CoordinateConverter.ConvertGeocoordinate(geocoordinate);
}
catch (System.UnauthorizedAccessException)
{
throw;
}
catch (TaskCanceledException)
{
throw;
}
catch (Exception)
{
throw;
}
}
else
{
return new GeoCoordinate();
}
}
public void SetMyLocation()
{
this.MyLocation = GetMyLocation().Result;
}
}
然后我从我的视图中调用它
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
_locationEntryViewModel.SetMyLocation();
}
我在一篇文章中读到,我再也找不到了,我不应该从我的 ViewModel 的构造函数中初始化它,所以为了测试目的,我把它放在 OnNavigateTo 中,但是如果有办法做到这一点,请让我知道,因为我觉得它会更有意义,不是吗?
谢谢。