1

MvvmLight の IDataService パターンを async/await で実現するクリーンな方法を見つけようとしています。

もともと、私はコールバック Action メソッドを使用してテンプレートと同様に動作していましたが、UI も更新されません。

public interface IDataService
{
    void GetData(Action<DataItem, Exception> callback);
    void GetLocationAsync(Action<Geoposition, Exception> callback);
}

public class DataService : IDataService
{
    public void GetData(Action<DataItem, Exception> callback)
    {
        // Use this to connect to the actual data service

        var item = new DataItem("Location App");
        callback(item, null);
    }

    public async void GetLocationAsync(Action<Geoposition, Exception> callback)
    {
        Windows.Devices.Geolocation.Geolocator locator = new Windows.Devices.Geolocation.Geolocator();
        var location = await locator.GetGeopositionAsync();
        callback(location, null);
    }
}

public class MainViewModel : ViewModelBase
{
    private readonly IDataService _dataService;

    private string _locationString = string.Empty;
    public string LocationString
    {
        get
        {
            return _locationString;
        }

        set
        {
            if (_locationString == value)
            {
                return;
            }

            _locationString = value;
            RaisePropertyChanged(LocationString);
        }
    }

    /// <summary>
    /// Initializes a new instance of the MainViewModel class.
    /// </summary>
    public MainViewModel(IDataService dataService)
    {
        _dataService = dataService;
        _dataService.GetLocation(
            (location, error) =>
            {
                LocationString = string.Format("({0}, {1})",
                location.Coordinate.Latitude,
                location.Coordinate.Longitude);
            });
    }
}

gps 座標に対してデータバインドしようとしていますが、非同期が発生し、メイン スレッドで実行されないため、UI は更新されません。

4

1 に答える 1

3

無関係かもしれませんが、引用符が欠落しているAFAICT

        RaisePropertyChanged(LocationString);

値ではなく、変更されたプロパティの名前を渡します。

于 2012-09-23T16:09:17.167 に答える