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 のコンストラクターからこれを初期化するべきではないという記事を読んだことがありますが、これを ViewModel のコンストラクターから初期化するべきではありません。私はそれがより理にかなっていると感じているので知っていますよね??
ありがとう。