Wpf模型通知循环 [英] Wpf model notification loop

查看:108
本文介绍了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模型通知循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆