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