是否有可能使用Prism从WPF应用程序中的不同ViewModels执行某种命令?从不同的ViewModel执行相同的Prism命令
让我解释一下我的意思。
我有MainMenuViewModel类:
public class MainMenuViewModel
{
private ICommand _aboutCommand;
public ICommand AboutCommand
{
get
{
if (_aboutCommand == null)
{
_aboutCommand = new DelegateCommand(() =>
{ MessageBox.Show("About menu item clicked!"); });
}
return _aboutCommand;
}
}
}
也有此模型的视图:
<Menu IsMainMenu="True">
<MenuItem Header="Nápověda">
<MenuItem Header="O Aplikaci" x:Name="About"
Command="{Binding AboutCommand}" />
</MenuItem>
</Menu>
有一个在应用程序的另一个模块,它应该具有相同的行为执行命令(甚至可能更好 - 相同的命令):
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>
是否有可能避免重复的代码?
P.S.我明白,我可以为这两个ViewModel创建基类,并在那里描述这个Commands,但问题是,一些ViewModel已经有了不同的基类。
我知道EventAggregator,但在这种情况下无法避免重复的代码。 – msi 2012-03-07 23:15:42
是的,它确实... MainMenuViewModel将实现显示关于菜单的代码。它还将订阅名为“AboutCommandFired”的事件,MunisatorViewModel将发布该事件。在您的MainMenuViewModel中,您可能还需要将实现移出匿名方法,以便可以从DelegateCommand和事件聚合器中调用它。 – lecrank 2012-03-07 23:48:13
但在这种情况下,我仍然应该复制创建命令的代码,并将不同的命令分配给视图。我的问题是,如果可以对不同的视图使用SAME Command实现。 – msi 2012-03-08 09:22:39