如果在视图模型中发生某些事情,我想在视图中执行某些代码。我已经研究了 Prism事件聚合器但是我没有成功使用棱镜5.如果有更简单的方法这样做会有所帮助。任何关于此的博客或相同代码也将起作用
答案 0 :(得分:2)
正如Ed Plunkett所说,要做的就是在视图中监听DataContextChanged,因为这就是View与ViewModels连接的方式。
以下是一个例子:
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
}
}