如何为特定按钮事件触发ViewModel命令

Sma*_*aug 8 wpf command button mvvm mouseevent

如何通过按钮的特定事件调用ViewModel上的命令,例如MouseDoubleClick

Mar*_*arc 23

您可以EventTriggerSystem.Windows.Interactivity命名空间中使用它,它是所谓的Prism框架的一部分.如果您刚刚开始使用MVVM,那么现在不要过多关注Prism,但请记住以后再考虑.无论如何,你可以钢铁了EventTrigger

它的工作原理如下:

引用程序集System.Windows.Interactivity.dll

在XAML中,引用命名空间:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
Run Code Online (Sandbox Code Playgroud)

然后在Button或任何其他控件中添加一个EventTrigger,如下所示:

<Button Content="Button">
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="MouseDoubleClick">
         <i:InvokeCommandAction Command="{Binding CommandToBindTo}" 
                                CommandParameter="{Binding CommandParameterToBindTo}" />
      </i:EventTrigger>
   </i:Interaction.Triggers>
</Button>
Run Code Online (Sandbox Code Playgroud)

这样,您就可以将事件绑定到DataContext上的Command.

备注

为了澄清用法,这里有一种真实的例子,包括ViewModel.虚构的要求是允许用户选择列表中的项目,然后执行将所选项目作为参数的命令:

<ListBox x:Name="ItemsList" ItemsSource="{Binding Items}" />

<Button Content="Do something with selected item">
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="MouseDoubleClick">
         <i:InvokeCommandAction Command="{Binding DoSomethingCommand}" 
                                CommandParameter="{Binding SelectedItem, 
                                                   ElementName=ItemsList}" />
      </i:EventTrigger>
   </i:Interaction.Triggers>
</Button>
Run Code Online (Sandbox Code Playgroud)

这就是ViewModel.注意如何使用命令的参数,DelegateCommand在每个MVVM框架中(有时RelayCommand)获取对象的通用版本的示例.此类将所需参数的类型作为通用参数(此处ItemViewModel),并且需要一个采用相应参数(此处ExecuteDoSomethingWithItem(ItemViewModel ...))的方法.其余的是WPF魔术:CommandParameter属性绑定在XAML中的对象将作为Execute(...)函数中的参数传递.

public class ViewModel
{
    ObservableCollection<ItemViewModel> Items { get; set; }

    public ICommand DoSomethingCommand
    {
        get
        {
            return _doSomethingCommand ??
                   (_doSomethingCommand = new DelegateCommand<ItemViewModel>(ExecuteDoSomethingWithItem));
        }
    }

    private DelegateCommand<ItemViewModel> _doSomethingCommand;

    private void ExecuteDoSomethingWithItem(ItemViewModel itemToDoSomethingWith)
    {
        // Do something
    }

    public ViewModel()
    {
        Items = new ObservableCollection<ItemViewModel>();
        // Fill the collection
    }
}
Run Code Online (Sandbox Code Playgroud)

学习MVVM玩得开心,值得.