我如何在WPF DataGrid上处理单元格双击事件,相当于Windows DataGrid的事件?

Vad*_*oft 8 wpf events datagrid cell

如您所知,在Windows C#的gridview中,如果我们想要在单元格上处理单击/双击事件,那么就会出现CellClick,CellDoubleClick等事件.

所以,我想和WPF DataGrid的windows gridview一样.我到目前为止搜索过,但这两个答案都不适用也没用.他们中的一些人说使用MouseDoubleClick事件但是,在这种情况下,我们必须检查每一行以及该行中的项目,因此检查每个单元格的数据和时间是非常耗时的.

我的DataGrid与DataTable绑定,AutoGeneratedColumn为False.如果您的答案基于AutoGeneratedColumn = True,则无法进行.甚至,我正在根据数据更改datagrid单元格的样式,因此无法更改AutoGeneratedColumn属性.

Cell Clicking/Double Clicking事件应该与windows grid的事件一样快.如果有可能那么告诉我如何,如果没有,那么可以选择做什么呢?

请帮我.....

非常感谢....

Ana*_*ali 5

另一种方法是定义a DataGridTemplateColumn而不是使用预定义列DataGridCheckBoxColumn,DataGridComboBoxColumn然后将事件处理程序添加到数据模板中定义的UI元素.

下面我MouseDownTextBlockCell 定义了一个事件处理程序.

<DataGrid AutoGenerateColumns="False">
    <DataGrid.Columns>

        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock MouseDown="TextBlock_MouseDown"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

在代码隐藏文件中:

private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
    TextBlock block = sender as TextBlock;
    if (block != null)
    {
        // Some Logic
        // block.Text
    }
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*w S 5

我知道这可能会晚一些,但是这可能对以后的其他人很有用。

在您的MyView.xaml中:

<DataGrid x:Name="MyDataGrid" ...>
    <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridCell}">
            <EventSetter Event="MouseDoubleClick" Handler="DataGridCell_MouseDoubleClick"/>
        </Style>
    </DataGrid.Resources>

    <!-- TODO: The rest of your DataGrid -->
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

在您的MyView.xaml.cs中:

private void DataGridCell_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    var dataGridCellTarget = (DataGridCell)sender;
    // TODO: Your logic here
}
Run Code Online (Sandbox Code Playgroud)

  • 优秀的答案 (3认同)

Ε Г*_*И О 3

我知道编写 WPF 有时是 PITA。无论如何,在这里你都必须处理该MouseDoubleClick事件。然后搜索源对象层次结构以找到 aDataGridRow并对其执行任何操作。

更新:示例代码

XAML

<dg:DataGrid MouseDoubleClick="OnDoubleClick" />
Run Code Online (Sandbox Code Playgroud)

代码隐藏

private void OnDoubleClick(object sender, MouseButtonEventArgs e)
{
    DependencyObject source = (DependencyObject) e.OriginalSource;
    var row = GetDataGridRowObject(source);
    if (row == null)
    {
         return;
    }
    else
    {
        // Do whatever with it
    }
    e.Handled = true;
}

private DataGridRow GetDataGridRowObject(DependencyObject source)                               
{
    // Write your own code to recursively traverse up via the source
    // until you find a DataGridRow object. Otherwise return null.
}
Run Code Online (Sandbox Code Playgroud)

}