Reputation: 451
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.
Upvotes: 4
Views: 8038
Reputation: 326
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.
Upvotes: 5
Reputation: 4914
You would need to either subscribe to the PropertyChanged
event of each dependency property (I.e. the properties that implement INotifyPropertyChanged
), or modify your MyViewModel
class to raise an event from the setters of the properties (dependency or otherwise) that you are interested in being notified about, and then subscribe to the common event.
Upvotes: 1