我目前正在尝试使用WPF和MVVM,但最近遇到了一个我不知道如何解决的问题.我对此并不陌生,所以如果事情不应该如此,请告诉我.
我有一个ParentView及其ParentViewModel. ParentView拥有两个视图SubViewA和SubViewB,它们都有自己的ViewModel.这是我的ParentView.xaml:
<local:ViewBase.DataContext>
<local:ParentViewModel x:Name="Model" />
</local:ViewBase.DataContext>
<Grid>
<local:SubViewA Visibility="{Binding ElementName=Model, Path=SubViewAVisibility}" />
<local:SubViewB Visibility="{Binding ElementName=Model, Path=SubViewBVisibility}" />
</Grid>
我想做什么:SubViewModelB具有绑定到SubViewB的属性.我想在ParentViewModel中发生某个事件时更改该属性.我想应该通过将SubViewModelB中的属性绑定到ParentViewModel中的属性来完成,但是我不确定如何?我在ParentView.xaml中尝试了以下内容:
<local:SubViewB Visibility="{Binding ElementName=Model, Path=SubViewBVisibility}" SomeProperty="{Binding ElementName=Model, Path=WhatIWantThePropertyToBe}" />
但这使我无处可去.
那么我该如何解决呢?我知道我可以通过MVVM light工具包中的消息传递来完成此操作,但这似乎与我要执行的操作不适当.有什么建议么?
谢谢
解决方法:
听起来像是解决EventAggregator模式的好方法.有一些很棒的实现,例如Microsoft Prism或TinyMessenger提供的实现(非常轻巧)
作为一个代码示例,您将执行以下操作(使用Prism,未经测试的代码)
public class ParentViewModel
{
private IEventAggregator eventAggregator;
public ParentViewModel(IEventAggregator eventAggregator)
{
this.eventAggregator = eventAggregator;
}
public void PublishSomeEvent()
{
// When a condition occurs, publish an event any subscribers
// that may be listening
this.eventAggregator.GetEvent<SomeEvent>()
.Publish(new SomeEvent("Hello World!")));
}
}
public class SubViewModel
{
private IEventAggregator eventAggregator;
public SubViewModel(IEventAggregator eventAggregator)
{
eventAggregator.GetEvent<SomeEvent>.SomeEvent(OnSomeEventOccurred);
}
public void OnSomeEventOccurred(SomeEvent arg)
{
// This method called when ParentViewModel publishes the event
Console.WriteLine(arg.OptionalMessage);
}
}
您将需要单独的事件声明.例如,我用这个
public SomeEvent : CompositePresentationEvent<SomeEvent>
{
public SomeEvent(string optionalMessage)
{
this.optionalMessage = optionalMessage;
}
public string OptionalMessage { get { return optionalMessage; } }
}