我正在为2个窗口创建2个相同型号的实例。进行通信的类名为manager。 我想在第一个窗口中更改属性时通知第二个窗口。该模型实现
Hi, I'm creating 2 instances of the same model for 2 windows. The class to make the communication is named 'manager'. I want to notify the second window when a property is changed in the first window. The model implements
INotifyPropertyChanged当值在第二次更改时,它正在提升事件
When the value is changed in the second, it's raising the event
public bool MyProperty { get { return _myProperty; } set { _myProperty = value; OnPropertyChanged(); } }
public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName]string caller = null) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(caller)); } }
在经理中,我会收到一个通知我正在更新模型的所有实例
In the manager, I'll receiving a notification and I'm updating all instances of the models
private void Vm_PropertyChanged(object sender, PropertyChangedEventArgs e) { var prop = TypeDescriptor.GetProperties(sender)[e.PropertyName]; if (prop != null) { object val = prop.GetValue(sender); SynchronizeViews(e.PropertyName, val); } } private void SynchronizeViews(string propertyName, object val) { foreach(MainViewModel vm in MainViewModelList) { vm.MyProperty = (bool)val; } }最后,它是不工作,因为我正在制作一个循环!!!! 我尝试过: 请参阅描述我尝试过的内容。
At the end, it's not working because I'm making a loop !!!! What I have tried: See the content of the message describing what I have tried.
推荐答案INotifyPropertyChanged用于从ViewModel与View进行通信,以及使用了很多外部逻辑。您可以通过创建Binding来完成所有工作,但只要模型在ViewModel观察到的更改发生时执行事件,可能会容易得多。当ViewModel收到更改通知时,它确保其值对应于Model中的新值。 你可以做的另一件事是在ViewModels中引用一个包含两个视图共享的属性的类,以及当一个视图进行更改时的方式,它正在更改此公共类中的值,并且该属性在更改时执行PropertyChanged事件。 The INotifyPropertyChanged is intended to communicate from a ViewModel to the View, and uses a lot of external logic. You could do all the stuff with creating a Binding, but it would probably be far easier to just have the model execute an event whenever a change occurs that is observed by both ViewModels. When a ViewModel is notified of the change it ensures that its value corresponds to the new value in the Model. Another thing you could do is have a reference in both ViewModels to a class that contains the properties that the two Views share, and that way when one view makes a change, it is changing the value in this common class, and that property, when changed executes the PropertyChanged event.
更多推荐
Wpf模型通知循环
发布评论