![](/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.