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



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

您可以在System.Windows中使用EventTrigger。交互命名空间,它是所谓的Prism框架的一部分。如果您刚刚开始使用MVVM,那么现在不必太关心Prism,但要记住它,以便以后使用。无论如何,你可以钢EventTrigger

它是这样工作的:

引用程序集 system . windows . interactive .dll

在XAML中引用命名空间:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

然后在你的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>

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

评论>

为了澄清用法,这里有一个现实生活中的例子,包括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>

那就是ViewModel。注意命令的参数是如何使用的,在示例中使用的是DelegateCommand对象的通用版本,因为您可以在每个MVVM框架(有时是RelayCommand)中获得它。这个类接受所需参数的类型作为泛型参数(这里是ItemViewModel),并需要一个接受相应参数(这里是ExecuteDoSomethingWithItem(ItemViewModel ...))的方法。其余的是WPF的魔力:在XAML中绑定CommandParameter属性的对象将作为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
    }
}

祝你学习MVVM愉快,这是值得的。

您可以使用附加的命令行为

=> http://geekswithblogs.net/HouseOfBilz/archive/2009/08/21/adventures-in-mvvm-ndash-generalized-command-behavior-attachments.aspx

如果要从现成的WPF中使用命令和事件绑定,则需要自己做大量的修饰。你可以使用现有的框架,如MVVM Light Toolkit或Cliburn Micro,它们已经提供了命令甚至绑定。

最新更新