从 WPF 中的视图观察 ViewModel 中的变量

Observe variable in ViewModel from View in WPF

我的 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();
}