[英]How do i handle cell double click event on WPF DataGrid, equivalent to windows DataGrid's Events?
如您所知,在 windows C# 的 gridview 中,如果我们要处理单元格上的单击/双击事件,则有 CellClick、CellDoubleClick 等事件。
所以,我想用 WPF DataGrid 做与 windows gridview 一样的事情。 到目前为止,我已经搜索过,但答案既不适用也不有用。 他们中的一些人说使用 MouseDoubleClick 事件,但在这种情况下,我们必须检查每一行以及该行中的项目,因此检查每个单元格的数据很耗时,时间在这里最重要。
我的 DataGrid 绑定到 DataTable 并且 AutoGeneratedColumn 为 False。 如果您的答案基于 AutoGeneratedColumn=True 那么这是不可能的。 甚至,我正在根据数据更改数据网格单元格的样式,因此无法更改 AutoGeneratedColumn 属性。
单元格单击/双击事件应该与 Windows 网格的事件一样快。 如果有可能,请告诉我如何操作,如果没有,那么有什么替代方法呢?
请帮我.....
非常感谢....
我知道这对派对来说可能有点晚了,但这可能对以后的其他人有用。
在您的 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
}
另一种方法是定义DataGridTemplateColumn
而不是使用预定义的列(如DataGridCheckBoxColumn
、 DataGridComboBoxColumn
,然后将事件处理程序添加到数据模板中定义的 UI 元素。
下面我为TextBlock
Cell 定义了一个MouseDown
事件处理程序。
<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
}
}
我知道编码 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.
}
}
我用过这样的东西:
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding ShowOverlay}" CommandParameter="{Binding Parameter}" />
</DataGrid.InputBindings>
并在我的视图模型中处理我的命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.