Wpf模型通知循环

编程入门 行业动态 更新时间:2024-10-15 06:21:42
本文介绍了Wpf模型通知循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在为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模型通知循环

本文发布于:2023-11-27 23:17:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639996.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   通知   Wpf

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!