Search code examples
c#wpfdatacontextinotifypropertychanged

Detecting property changes on a datacontext


A further question to Clemen's fine answer here: DataContext values in view code behind. If one used this approach, is it possible to detect property changes on the VM at this point? These are correctly implemented through INotifyPropertyChanged.

var viewModel = DataContext as MyViewModel;
//How would one detect a property change on viewModel?
//Tried viewModel.PropertyChange which doesn't fire.

Solution

  • I think you must be doing something wrong that you're not mentioning in your post. The following code works as expected and will print MyTestPropertyName to the Console window.

    public partial class MainWindow : Window
    {
    
        public MainWindow()
        {
            DataContext = new MyViewModel();
        }
    
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            MyViewModel viewModel = DataContext as MyViewModel;
            viewModel.PropertyChanged += MyPropertyChangedEventHandler;
            viewModel.NotifyPropertyChanged();
        }
    
        private void MyPropertyChangedEventHandler(object sender, PropertyChangedEventArgs e)
        {
            Console.WriteLine(e.PropertyName);
        }
    
    }
    
    public class MyViewModel : INotifyPropertyChanged
    {
        public void NotifyPropertyChanged()
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs("MyTestPropertyName"));
            }
        }
    
        #region INotifyPropertyChanged Members
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        #endregion
    }
    

    It should be noted that this is TERRIBLE design, and is only designed as a proof of concept, that you can indeed subscribe to events on the ViewModel in the code-behind.