是否可以使用 Prism 从 WPF 应用程序中的不同 ViewModel 以某种方式执行一个命令?
让我解释一下我的意思。
我有 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;
}
}
}
还有这个模型的 View :
<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;
}
}
}
这个模块有 View :
<StackPanel Background="White" HorizontalAlignment="Center" VerticalAlignment="Top">
<Button cmd:Click.Command="{Binding AboutCommandInAnotherModule}">About</Button>
</StackPanel>
是否可以避免重复代码?
附言我知道,我可以为这两个 ViewModel 创建基类并在那里描述这个命令,但问题是,一些 ViewModel 已经有不同的基类。
最佳答案
使用 EventAggregator 来引发这样的事件。这允许您在 UI 的不同区域之间进行松散耦合的通信。
发布/订阅概念,通过实现 CompositeEvent 对象传递数据效果很好。
或者,您可以将您的命令设为静态并从不同区域访问它,但这似乎并不那么好。
Prism documentation详细说明您的选择。
希望有帮助。
关于c# - 从不同的 ViewModel 执行相同的 Prism 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9610257/