【问题标题】:DataGrid bind command to cell clickDataGrid 绑定命令到单元格单击
【发布时间】:2013-08-18 17:50:11
【问题描述】:

这是一个简单的问题。我有一个如下所示的 DataGrid:

<DataGrid ItemsSource="{Binding Path=Sections}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Path=ImportName, Mode=OneWay}" Header="Imported" />
        <DataGridTextColumn Binding="{Binding Path=FoundName, Mode=TwoWay}" Header="Suggested" />
    </DataGrid.Columns>
</DataGrid>

我想将“建议”列单元格绑定到我的 VM 中的命令,以便每次用户单击单元格进行编辑时,我的命令都会执行并为用户显示一个对话框。对于此处描述的类似问题,我找到了一个有趣的解决方案:DataGrid bind command to row select

我喜欢它从 XAML 进行管理的事实,而无需任何附加到单元格编辑事件的代码隐藏。不幸的是,我不知道如何将它转换为允许我将命令绑定到特定列中的单元格,而不是整行。对此有何建议?

【问题讨论】:

    标签: wpf binding datagrid triggers


    【解决方案1】:

    您可以使用DataGrid 控件中的BeginningEdit 事件来处理这种情况。此事件将在行或单元格进入编辑模式之前触发。您可以从 EventArgs 中识别选定的列。 示例:

    private void dgName_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
            {
                if (e.Column.Header.ToString() == "Suggested")
                {
                    //Do Operation
                }
            }
    

    如果您使用 MVVM 模式,则可以选择将 EventArgs 传递给 VM。如果您使用的是 MVVMLight Toolkit,则有一个名为 PassEventArgs 的选项并将其设置为 TRUE

    在虚拟机中,

    //中继命令

    private RelayCommand<DataGridBeginningEditEventArgs> _cellBeginningEditCommand;
        public RelayCommand<DataGridBeginningEditEventArgs> CellBeginningEditCommand
        {
            get
            {
                return _cellBeginningEditCommand ?? (_cellBeginningEditCommand = new RelayCommand<DataGridBeginningEditEventArgs>(CellBeginningEditMethod));
            }
        }
    

    //命令处理程序

    private void CellBeginningEditMethod(DataGridBeginningEditEventArgs args)
            {
                if(args.Column.Header.ToString() == "Suggested")
                {
                    //Do Operation
                }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 2014-06-17
      • 2010-10-24
      • 2023-04-03
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多