c# - 从不同的 ViewModel 执行相同的 Prism 命令

标签 c# wpf mvvm prism

是否可以使用 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/

相关文章:

C# - 垃圾回收

c# - SPGridView 中日期/时间的 ObjectDataSource 过滤

c# - WPF - 具有可扩展控制切碎元素的面板

c# - WPF UserControl 组件网格定义问题

c# - 寻找有关在 WPF MVVM 应用程序中放置一些代码的指导

c# - Xamarin 删除应用标题

c# - 使用扩展方法将字符串转换为十进制

WPF ListView - 按嵌套属性排序

silverlight - MVVM 问题 - 仅绑定(bind)某些值

wpf - 使用MVVM在WPF DataGrid中显示组合框的用户友好方法