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

问题描述 投票:8回答:3

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

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

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

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

请帮我.....

非常感谢....

wpf events datagrid cell
3个回答
5
投票

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

下面我为MouseDown Cell定义了一个TextBlock事件处理程序。

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

        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock MouseDown="TextBlock_MouseDown"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

在代码隐藏文件中:

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

4
投票

我知道这对派对来说可能有点晚了,但这可能对其他人有用。

在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>

在MyView.xaml.cs中:

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

3
投票

我知道编码WPF有时候是PITA。无论如何,你必须处理MouseDoubleClick事件。然后搜索源对象层次结构以查找DataGridRow并对其执行任何操作。

更新:示例代码

XAML

<dg:DataGrid MouseDoubleClick="OnDoubleClick" />

代码背后

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.
}

}

© www.soinside.com 2019 - 2024. All rights reserved.