具有异步等待的MvvmLight IDataService

时间:2012-09-23 12:21:01

标签: c#-4.0 mvvm-light async-await

我正在尝试使用async / await找到一种干净的方法来完成MvvmLight的IDataService模式。

最初我使用回调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。

1 个答案:

答案 0 :(得分:3)

可能不相关,但AFAICT你错过了一些引用

        RaisePropertyChanged(LocationString);

您传递已更改的属性的名称,而不是其值。