Home > database >  Observe variable in ViewModel from View in WPF
Observe variable in ViewModel from View in WPF

Time:02-24

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.

CodePudding user response:

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 a PropertyChanged 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's Loaded event.

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

Perhaps you don't need the PropertyChanged handling at all. Assuming that LoginStatus is updated by the GetReadyForUnlockWithBLEAsync method, this may also work:

public MainWindow()
{
    InitializeComponent();

    ViewModel = new AuthenticationViewModel();

    Loaded  = OnWindowLoaded;
}

private async void OnWindowLoaded(object sender, RoutedEventArgs e)
{
    await ViewModel.GetReadyForUnlockWithBLEAsync();

    AuthenticationSuccess();
}
  • Related