代码之家  ›  专栏  ›  技术社区  ›  Bassie

如何在双击时简单地将当前选定的DataGridRow项发送到ViewModel中的ICommand

  •  2
  • Bassie  · 技术社区  · 7 年前

    是否可以发送当前选定的 DataGridRow 双击 InputBinding ?

    我看到这个了

    <DataGrid ItemsSource="{Binding Consignments}" 
                x:Name="dataGridConsignments" 
                Margin="10,47,10,9.6"
                IsReadOnly="True" ColumnWidth="*" AutoGenerateColumns="False"
                xmlns:DataGridDoubleClickCommand="{Binding DataGridDoubleClick}">
        <DataGrid.InputBindings>
            <MouseBinding Gesture="LeftDoubleClick"  Command="{Binding RowDoubleClick}"/>
        </DataGrid.InputBindings>
    
    ...
    

    视图模型包含

    private ICommand rowDoubleClick;
    public ICommand RowDoubleClick
    {
        get
        {
            return rowDoubleClick
                ?? (rowDoubleClick= new ActionCommand(() =>
                {
                    // I need the selected row here
                    MessageBox.Show("asd");
                }));
        }
    }
    

    用这个 ActionCommand 实施:

    public class ActionCommand : ICommand
    {
        private readonly Action _action;
    
        public ActionCommand(Action action)
        {
            _action = action;
        }
    
        public void Execute(object parameter)
        {
            _action();
        }
    
        public bool CanExecute(object parameter)
        {
            return true;
        }
    
        public event EventHandler CanExecuteChanged;
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Nik    7 年前

    你可以用 CommandParameter .

    <MouseBinding Gesture="LeftDoubleClick" Command="{Binding RowDoubleClick}"
       CommandParameter="{Binding ElementName=dataGridConsignments, Path=SelectedItem}"/>
    

    这样做需要您执行 ICommand 接口,以便 Action 接受一个参数。您可以看到的标准实现和用法 RelayCommand here . 这和你所做的非常相似 ActionCommand 但它允许在代码中使用参数。

    或者,您可以简单地绑定 SelectedItem 你的 DataGrid 到视图模型中的属性,并在命令触发时使用该属性。

    <DataGrid ItemsSource="{Binding Consignments}" SelectedItem="{Binding VMSelectedItem}" ../>
    

    对于任何一种方法,请记住,如果在 数据网格 ,所选项目将 null ,因此在对属性/参数进行操作之前,需要执行空检查。

        2
  •  2
  •   Petar Stojanovski    7 年前

    您可以尝试将此行添加到数据报

    ItemsSource="{Binding Consignments}" SelectedItem="{Binding SelectedConsignment}"
    

    请记住通知“OnPropertyChanged”。