1
我试图找到一种干净的方式来完成异步/等待MvvmLight的IDataService模式。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。
Mvvmlight的魔力并不需要这个。 –
AFAICT您在ObservableObject中调用受保护的虚拟无效RaisePropertyChanged(string propertyName)。你是否打算调用Expression版本和pass()=> LocationString或类似的? http://mvvmlight.codeplex.com/SourceControl/changeset/view/b922e8ccf674#GalaSoft.MvvmLight%2fGalaSoft.MvvmLight%20%28NET35%29%2fObservableObject.cs –
@jeremy James是对的。如果你试图在你的LocationString属性上引发PropertyChanged事件,那么你必须像这样调用方法'RaisePropertyChanged(“LocationString”)'或者如果你想避免输入字符串,就像这样'var expression =()=> LocationString; ''RaisePropertyChanged(expression.Member.Name)' – bugged87