将事件绑定到没有Blend SDK或第三方的命令。 (WPF / MVVM)

时间:2018-01-25 14:07:49

标签: c# wpf mvvm wpf-controls wpfdatagrid

有没有办法将事件绑定到命令没有 System.Windows.Interactivity或任何其他第三方库?

到目前为止,我已尝试过以下内容:

<Style TargetType="DataGridRow">
      <EventSetter Event="MouseDoubleClick"
      Handler="{Binding DoubleClickCommand}" />
</Style>

<DataGrid.InputBindings>
      <MouseBinding Gesture="LeftDoubleClick" Command="{Binding DoubleClickCommand}"/>
</DataGrid.InputBindings>

<DataGrid ItemsSource="{Binding Model.SpectrumCollections}"
          ColumnWidth="*"
          AutoGenerateColumns="false"
          IsReadOnly="True" 
          BorderThickness="0"
          HeadersVisibility="Column" MouseDoubleClick="{Binding DoubleClickCommand}">

但是看起来没有用,任何帮助都会受到高度赞赏。

编辑1: 这是我使用的RelayCommand的实现,也许问题就在那里..

public class RelayCommand : ICommand
{
    private readonly Func<bool> _canExecute;

    private readonly Action _execute;

    public RelayCommand(Action inExecute, Func<bool> inCanExecute = null)
    {
        _execute = inExecute ?? throw new Helper.Exceptions.DelegateCommandException(
                       Exceptions.InExecuteIsNullException);
        _canExecute = inCanExecute;
    }

    public event EventHandler CanExecuteChanged
    {
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }

    public bool CanExecute(object inObject) => _canExecute?.Invoke() ?? true;

    public void Execute(object inObject) => _execute?.Invoke();
}

1 个答案:

答案 0 :(得分:1)

您无法执行以下操作,因为MouseDoubleClick是en事件而不是依赖项属性:

MouseDoubleClick="{Binding DoubleClickCommand}">

您可以绑定到Command的{​​{1}}属性,但是:

MouseBinding

如果要在双击单元格时调用该命令,则应将<DataGrid.InputBindings> <MouseBinding Gesture="LeftDoubleClick" Command="{Binding DoubleClickCommand}"/> </DataGrid.InputBindings> 添加到MouseBinding

DataGridCell