从 WPF 中的 View 观察 ViewModel 中的变量
我的 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 中获取其更新值。
I have a boolean variable in my ViewModel and I want to observe any changes to it.
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));
}
}
}
I am trying to use it in my View as following:
public MainWindow()
{
InitializeComponent();
ViewModel = new AuthenticationViewModel();
_ = ViewModel.GetReadyForUnlockWithBLEAsync();
if(ViewModel.LoginStatus)
{
AuthenticationSuccess();
}
}
But I am not able to observe the variable from ViewModel. I can't get its updated value in View on any changes in ViewModel.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建视图模型后,MainWindow 构造函数中的代码会检查一次
LoginStatus
属性的值。没有任何东西可以注册PropertyChanged
事件,例如数据绑定。您可以手动注册一个
PropertyChanged
处理程序,如下所示,并在窗口的Loaded
事件的异步处理程序中等待可等待方法调用。也许您根本不需要
PropertyChanged
处理。假设通过GetReadyForUnlockWithBLEAsync
方法更新了LoginStatus
,这也可能有效:The code in your MainWindow constructor checks the value of the
LoginStatus
property once after creating the view model. There is nothing that would register aPropertyChanged
event, like for example a data binding.You may manually register a
PropertyChanged
handler like shown below, and also await the awaitable method call in an async handler of the Window'sLoaded
event.Perhaps you don't need the
PropertyChanged
handling at all. Assuming thatLoginStatus
is updated by theGetReadyForUnlockWithBLEAsync
method, this may also work: