我的 ViewModel 中有一個布爾變數,我想觀察它的任何變化。視圖模型:
internal class AuthenticationViewModel : ViewModelBase
{
APIClient apiClient;
bool _loginStatus;
public AuthenticationViewModel()
{
}
public bool LoginStatus { get { return _loginStatus; }
set {
_loginStatus = value;
NotifyPropertyChanged("LoginStatus");
} }
}
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
我正在嘗試在我的視圖中使用它,如下所示:
public MainWindow()
{
InitializeComponent();
ViewModel = new AuthenticationViewModel();
_ = ViewModel.GetReadyForUnlockWithBLEAsync();
if(ViewModel.LoginStatus)
{
AuthenticationSuccess();
}
}
但我無法從 ViewModel 觀察變數。在 ViewModel 中發生任何更改時,我都無法在 View 中獲取其更新值。
uj5u.com熱心網友回復:
MainWindow 建構式中的代碼在LoginStatus創建視圖模型后檢查一次屬性的值。沒有任何東西可以注冊PropertyChanged事件,例如資料系結。
您可以手動注冊一個PropertyChanged如下所示的處理程式,也可以在 WindowLoaded事件的異步處理程式中等待可等待的方法呼叫。
public MainWindow()
{
InitializeComponent();
ViewModel = new AuthenticationViewModel();
ViewModel.PropertyChanged = OnViewModelPropertyChanged;
Loaded = OnWindowLoaded;
}
private async void OnWindowLoaded(object sender, RoutedEventArgs e)
{
await ViewModel.GetReadyForUnlockWithBLEAsync();
}
private void OnViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(ViewModel.LoginStatus))
{
AuthenticationSuccess();
}
}
也許你根本不需要PropertyChanged處理。假設LoginStatus由GetReadyForUnlockWithBLEAsync方法更新,這也可能有效:
public MainWindow()
{
InitializeComponent();
ViewModel = new AuthenticationViewModel();
Loaded = OnWindowLoaded;
}
private async void OnWindowLoaded(object sender, RoutedEventArgs e)
{
await ViewModel.GetReadyForUnlockWithBLEAsync();
AuthenticationSuccess();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/436202.html
下一篇:異步方法作為同步方法作業
