I want to execute certain code in view if something happens in view model . I have looked into Prism event aggregator but I havent got success with prism 5. If there is more easier method to do so it will be helpful.Any blog or same code regarding this will also work
Asked
Active
Viewed 704 times
0
-
Please have a look that entry: http://stackoverflow.com/questions/15439841/mvvm-in-wpf-how-to-alert-viewmodel-of-changes-in-model-or-should-i?rq=1 – Ugur Apr 29 '16 at 11:41
-
2INotifyPropertyChanged is the way to go. Or regular events. In the view, add a DataContextChanged handler. When you get the datacontext, cast it to your viewmodel type and add handlers for PropertyChanged or whatever. – 15ee8f99-57ff-4f92-890c-b56153 Apr 29 '16 at 11:45
1 Answers
2
As Ed Plunkett says, the thing to do is listen for DataContextChanged in your view, as this is how View's are connected to ViewModels.
Here's an example:
public partial class MyView : UserControl
{
public MyView ()
{
DataContextChanged += MyView_DataContextChanged;
}
private void MyView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
//new ViewModel has been set.
MyViewModel myViewModel = e.NewValue as MyViewModel;
if (myViewModel != null)
{
//check for property changes
myViewModel.PropertyChanged += MyViewModel_PropertyChanged;
//custom event for specific update
myViewModel.MyCustomEventTriggered += MyViewModel_MyCustomEventTriggered
}
}
private void MyViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
//do your logic
}
private void MyViewModel_MyCustomEventTriggered(object sender, MyCustomEventArgs e)
{
//do your logic
}
}

Joe
- 6,773
- 2
- 47
- 81