我仍然开始使用MVVM并阅读所有MSDN Prism示例,但我仍然喜欢以下设计问题的一些指导,我觉得这将有助于我抓住Prism概念并强化什么我刚刚学会了
我有一个多窗口应用程序 - 每个窗口都有一个过滤器下拉控件。此过滤器控件的值将影响同一窗口中其他控件的显示,例如网格,图表等。
某些交互(例如双击网格上的一行)将产生另一个窗口,该窗口将有自己独立的过滤器控件,这同样会影响仅在该窗口内显示其他控件
如何实现过滤器的这种行为,驱动其不知道的其他用户控件的显示,并将其行为仅限于托管它的窗口?如何保持这些交互松散耦合?
我认为我需要使用EventAggregator并使用过滤器控件在选择更改时发布更新事件?我是否正确地思考这个问题?每个窗口都需要一个单独的EventAggregator吗?
答案 0 :(得分:2)
您应该使用EventAggregator
发布过滤器通知,这是从我的经验中做到这一点的最佳方式。您应该只使用一个EventAggregator
作为所有订阅对象之间的中心。
类似的东西:
MyNotificationChangedArgs args = new MyNotificationChangedArgs();
args.Payload = GetThePayload(someParameters);
myEventAggregator.GetEvent<NotificationFilterChangedEvent>().Publish(args);
真正有用的另一件事是依赖注入EventAggregator
,例如通过Unity
。这样,您的所有控件都可以通过调用EventAggregator
方法访问公共UnityContainer.Resolve
:
var myEventAggregator = myUnityContainer.Resolve<MyEventAggregator>();
答案 1 :(得分:2)
是的,你正在考虑这个正确的方法。 EventAggregator是您正在做的事情的好工具。您需要在计划从中提出事件的每个窗口上安装EventAggregator。您可以将EA注入构造函数或使用ServiceLocator。以下是两个例子:
// Ctor injection
private IEventAggregator _eventAggregator;
public ViewModelBase(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
}
// Service Locator
ServiceLocator.Current.GetInstance<IEventAggregator>().GetEvent<YourEvent>().Publish();
现在,您需要为要发布的EA创建CompositePresentationEvent。您可以通过在CPE中包含有效负载来最小化创建的数量。像这样:
public class NavigationSelectedEvent : CompositePresentationEvent<NavigationEnum.Destination>{}
现在您已准备好发布活动:
_eventAggregator.GetEvent<NavigationSelectedEvent>().Publish(NavigationEnum.Destination.Home);
然后订阅它 - 使用有效负载上的可选过滤器,这样你就不会浪费资源:
this.EventAggregator.GetEvent<NavigationSelectedEvent>().Subscribe(HandleNavigationEvent, ThreadOption.UIThread, false, i => i == NavigationEnum.Destination.Home);
答案 2 :(得分:1)
每个View都可以通过ViewModel访问Model。为过滤器建模。然后,Views绑定到使用过滤器的ViewModel表示。您的视图不必彼此了解,只需绑定到模型。