简体   繁体   English

当复选框未选中或发生事件时,如何通知多个视图模型? C# WPF

[英]How to notify more than one View models when checkbox is unchecked or on an event? C# WPF

There are checkbox's in MainWindow (and MainWindowVM) on check of it other windows(But not all) should be notified, Current we are doing by handling events. MainWindow(和 MainWindowVM)中有复选框检查它应该通知其他窗口(但不是全部),当前我们正在通过处理事件来做。 that is each VM will subscribe to an event and whenever changes happen we will handle it in all VM's is there any better way of doing it?也就是说,每个 VM 都会订阅一个事件,每当发生变化时,我们都会在所有 VM 中处理它,有没有更好的方法来做到这一点?

is there any better way of doing it?有没有更好的方法呢?

Use an event aggregator or a messenger .使用事件聚合器信使

This removes the tight coupling between the publishers and the subscribers.这消除了发布者和订阅者之间的紧密耦合。 The subscriber of an event observes the event aggregator instead of the publisher and the publisher knows only about the event aggregator and not about the different subscribers.事件的订阅者观察事件聚合器而不是发布者,发布者只知道事件聚合器而不知道不同的订阅者。

This leads to code that is a lot easier to maintain.这导致代码更容易维护。 Please refer to the links for more information.请参阅链接以获取更多信息。

You can use, what you already have, so subscribe for PropertyChanged of VM for MainWindow:你可以使用你已经拥有的东西,所以为 MainWindow 订阅 VM 的 PropertyChanged:

public class NonMainWindowVM : INotifyPropertyChanged
{
    public NonMainWindowVM(MainWindowVM mwVM)
    {
        mwVM.PropertyChanged += MW_PropertyChanged;
    }

    private void MW_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        switch (e.PropertyName)
        {
            case nameof(MainWindowVM.ID):
                //logic MainWindowVM.ID changed
                break;
            default:
                break;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM