我很难理解如何让多个窗口使用 MVVM 模式相互通信。
我有我的父窗口 P 和两个名为 C1 和 C2 的子窗口。我想要实现的是,当 C1 更改 P 共有的属性时,P 会收到通知并将其传达给 C2。
我不想使用通用的 ViewModel,因为我想找到一个可以轻松扩展的解决方案,而且我什至不想强制 C1 具有与 P 和 C2 相同的字段名称。
这将应用于可插入工具包,我或其他人可以在其中创建新组件的程序集(例如窗口),并订阅以在主窗口或另一个组件更改公共(public)元素时收到通知。
我是否缺少某种模式?
最佳答案
我会使用Prism来实现这一点。
这是一个例子:
将引发事件的类:
public class MainViewModel
{
public void UpdateName(string name)
{
Utility.EventAggregator.GetEvent<UpdateNameEvent>().Publish(name);
}
}
两个类(class)将订阅此事件:
public class Child1ViewModel
{
public string Name { get; set; }
public Child1ViewModel()
{
Utility.EventAggregator.GetEvent<UpdateNameEvent>().Subscribe(UpdateName);
}
private void UpdateName(string name)
{
this.Name = name;
}
}
和
public class Child2ViewModel
{
public string Name { get; set; }
public Child2ViewModel()
{
Utility.EventAggregator.GetEvent<UpdateNameEvent>().Subscribe(UpdateName);
}
private void UpdateName(string name)
{
this.Name = name;
}
}
EventAggregator 是 Prism.Events 的一部分,位于此处:
public class Utility
{
public static EventAggregator EventAggregator { get; set; }
static Utility()
{
EventAggregator = new EventAggregator();
}
}
事件的定义如下:
public class UpdateNameEvent : PubSubEvent<string>
{
}
现在尝试一下:
static void Main(string[] args)
{
MainViewModel mainViewModel = new MainViewModel();
Child1ViewModel child1 = new Child1ViewModel();
Child2ViewModel child2 = new Child2ViewModel();
mainViewModel.UpdateName("Name1");
Console.WriteLine(child1.Name);
Console.WriteLine(child2.Name);
}
在此示例中,我使用控制台应用程序。速度更快,还有一个字符串参数,但您可以根据需要替换它。 无论是 MVVM 方法还是任何其他模式,您都可以轻松实现这种通信。
在Nuget的帮助下安装Prism.Core,您将获得Prism dll的引用。
再一次:MainViewModel 将发布该事件,并且两个子级将订阅该事件。
就是这样。
关于c# - WPF:MVVM 上窗口之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50691794/