我的ViewModel中有一个布尔变量,我想观察它的任何更改。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中获取其更新值。
MainWindow构造函数中的代码在创建视图模型后检查LoginStatus
属性的值一次。没有什么可以注册PropertyChanged
事件,例如数据绑定。
您可以手动注册一个PropertyChanged
处理程序,如下所示,也可以在Window的Loaded
事件的异步处理程序中等待不可用的方法调用。
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();
}