12

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

所以,我想做与带有 WPF DataGrid 的 windows gridview 一样的操作。到目前为止我已经搜索过,但答案既不适用也不有用。他们中的一些人说使用 MouseDoubleClick 事件,但是在这种情况下,我们必须检查每一行以及该行中的项目,因此检查每个单元格的数据非常耗时,而且时间在这里是最重要的。

我的 DataGrid 绑定到 DataTable 并且 AutoGeneratedColumn 为 False。如果您的答案基于 AutoGeneratedColumn=True ,那么这是不可能的。甚至,我正在根据数据更改数据网格单元格的样式,因此无法更改 AutoGeneratedColumn 属性。

单元格单击/双击事件应该与 windows 网格的事件一样快。如果有可能,那么告诉我怎么做,如果没有,那么有什么替代方法呢?

请帮我.....

非常感谢....

4

4 回答 4

13

我知道这对聚会来说可能有点晚了,但这可能对以后的其他人有用。

在您的 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
}
于 2017-11-10T17:11:14.920 回答
5

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

下面我为Cell定义了一个MouseDown事件处理程序。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
    }
}
于 2013-01-28T08:32:00.510 回答
3

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

更新:示例代码

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

}

于 2013-01-28T08:06:15.900 回答
0

我用过这样的东西:

<DataGrid.InputBindings>
    <MouseBinding Gesture="LeftDoubleClick" Command="{Binding ShowOverlay}" CommandParameter="{Binding Parameter}" />
</DataGrid.InputBindings>

并在我的视图模型中处理我的命令。

于 2021-06-03T21:32:46.090 回答