![](/img/trans.png)
[英]Binding viewmodel property to view property in code behind using Prism
[英]Property change in Base ViewModel with prism
我正在使用棱镜开发一个Android应用程序。
我正在尝试制作基本ViewModel。 在此ViewModel中,我想为所有ViewModel设置通用属性。
public class BaseViewModel : BindableBase
{
protected INavigationService _navigationService;
protected IPageDialogService _dialogService;
public BaseViewModel(INavigationService navigationService, IPageDialogService dialogService)
{
_navigationService = navigationService;
_dialogService = dialogService;
}
private string _common;
/// <summary>
/// Common property
/// </summary>
public string CommonProperty
{
get { return _common; }
set
{
_common = value;
SetProperty(ref _common, value);
}
}
}
我的问题是:当我在构造函数中设置通用属性时,工作正常。 但是,当我在OnNavigatingTo
设置通用属性并使用async时,它不起作用。 调用OnNavigatingTo
时会触发SetProperty
,但是具有此公共属性的绑定标签不会刷新该值。
namespace TaskMobile.ViewModels.Tasks
{
/// <summary>
/// Specific view model
/// </summary>
public class AssignedViewModel : BaseViewModel, INavigatingAware
{
public AssignedViewModel(INavigationService navigationService, IPageDialogService dialogService) : base(navigationService,dialogService)
{
CommonProperty= "Jorge Tinoco"; // This works
}
public async void OnNavigatingTo(NavigationParameters parameters)
{
try
{
Models.Vehicle Current = await App.SettingsInDb.CurrentVehicle();
CommonProperty= Current.NameToShow; //This doesn´t works
}
catch (Exception e)
{
App.LogToDb.Error(e);
}
}
}
由于您是在单独的线程上进行异步调用,因此不会向UI通知更改。
不是事件处理程序的OnNavigatingTo
async void
,意味着它是在单独的线程中运行的即发即OnNavigatingTo
功能。
创建一个适当的事件和异步事件处理程序以在那里执行异步操作
例如
public class AssignedViewModel : BaseViewModel, INavigatingAware {
public AssignedViewModel(INavigationService navigationService, IPageDialogService dialogService)
: base(navigationService, dialogService) {
//Subscribe to event
this.navigatedTo += onNavigated;
}
public void OnNavigatingTo(NavigationParameters parameters) {
navigatedTo(this, EventArgs.Empty); //Raise event
}
private event EventHandler navigatedTo = degelate { };
private async void onNavigated(object sender, EventArgs args) {
try {
Models.Vehicle Current = await App.SettingsInDb.CurrentVehicle();
CommonProperty = Current.NameToShow; //On UI Thread
} catch (Exception e) {
App.LogToDb.Error(e);
}
}
}
这样,当等待的操作完成时,代码将在UI线程上继续,并且它将获取属性更改通知。
使用SetProperty时,不应为后场设置值。 因此,您应该删除以下行:
_common = value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.