从不同的ViewModels执行相同的棱镜命令 [英] Execute same Prism Command from different ViewModels
问题描述
是否有可能使用棱镜在WPF应用程序不同的ViewModels不知何故一个命令执行?
Is it possible to execute somehow one Command from a different ViewModels in the WPF application using Prism?
让我解释一下我的意思。
Let me explain what I mean.
我有MainMenuViewModel类:
I have the MainMenuViewModel class:
public class MainMenuViewModel
{
private ICommand _aboutCommand;
public ICommand AboutCommand
{
get
{
if (_aboutCommand == null)
{
_aboutCommand = new DelegateCommand(() =>
{ MessageBox.Show("About menu item clicked!"); });
}
return _aboutCommand;
}
}
}
还没有为观这种模式:
also there is the View for this model:
<Menu IsMainMenu="True">
<MenuItem Header="Nápověda">
<MenuItem Header="O Aplikaci" x:Name="About"
Command="{Binding AboutCommand}" />
</MenuItem>
</Menu>
有是在应用程序的另一个模块,它应具有相同的行为执行命令(或甚至可能是更好的 - 同样的命令):
There is another module in the application, which should execute the command with the same behavior (or even probably better - the same command):
public class MunisatorViewModel
{
private ICommand _aboutCommandInAnotherModule;
public ICommand AboutCommandInAnotherModule
{
get
{
if (_aboutCommandInAnotherModule== null)
{
_aboutCommandInAnotherModule= new DelegateCommand(() =>
{ MessageBox.Show("About menu item clicked!"); });
}
return _aboutCommandInAnotherModule;
}
}
}
本模块具有查看:
<StackPanel Background="White" HorizontalAlignment="Center" VerticalAlignment="Top">
<Button cmd:Click.Command="{Binding AboutCommandInAnotherModule}">About</Button>
</StackPanel>
是否有可能避免重复的代码?
Is it possible to avoid the duplicate code?
PS我明白了,我可以创建这个两的ViewModels基类,描述这个命令存在,但问题是,一些的ViewModels的早已不同的基类。
P.S. I understand, that I can create base class for this two ViewModels and describe this Commands there, but problem is, that some of the ViewModels has already different base classes.
推荐答案
使用的EventAggregator提出这样的事件。这可以让你有用户界面的不同区域之间的松耦合的沟通。
Use the EventAggregator to raise events like this. This allows you to have loosely coupled communication between different areas of the UI.
发布/订阅的概念,传递数据通过实施CompositeEvent对象效果很好。
The publish/subscribe concept, passing data through implementing a CompositeEvent object works well.
另外,你可以让你的命令静态和不同地区的访问,但似乎这并不是所有的美好。
Alternatively, you can make your command static and access it from different areas but this doesn't seem all that nice.
棱镜文档详细深入你的选择
希望有所帮助。
这篇关于从不同的ViewModels执行相同的棱镜命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!