wpf 检测数据上下文上的属性更改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13785282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detecting property changes on a datacontext
提问by John Sourcer
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.
此处 Clemen 的好答案的另一个问题:视图代码中的 DataContext values in. 如果使用这种方法,此时是否可以检测到 VM 上的属性更改?这些都是通过INotifyPropertyChanged.
var viewModel = DataContext as MyViewModel;
//How would one detect a property change on viewModel?
//Tried viewModel.PropertyChange which doesn't fire.
采纳答案by Rob Ocel
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.
我认为你一定做错了什么,你没有在你的帖子中提到。以下代码按预期工作,并将 MyTestPropertyName 打印到控制台窗口。
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.
应该注意的是,这是一个糟糕的设计,并且只是作为概念证明而设计的,您确实可以在代码隐藏中订阅 ViewModel 上的事件。
回答by Chamila Chulatunga
You would need to either subscribe to the PropertyChangedevent of each dependency property (I.e. the properties that implement INotifyPropertyChanged), or modify your MyViewModelclass 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.
您需要订阅PropertyChanged每个依赖属性(即实现 的属性INotifyPropertyChanged)MyViewModel的事件,或者修改您的类以从您有兴趣收到通知的属性(依赖或其他)的 setter 中引发事件,并且然后订阅公共事件。

