以编程方式WPF DataGrid行双击事件 [英] WPF DataGrid row double click event programmatically
问题描述
我需要以编程方式创建一个DataGrid,并需要添加一个双击行事件。在C#中怎么做?我发现这个;
I need to programmatically create a DataGrid and need to add a double click row event to it. How is this done in C#? I found this;
myRow.MouseDoubleClick += new RoutedEventHandler(Row_DoubleClick);
虽然这对我来说不起作用,因为我绑定了 DataGrid.ItemsSource
到一个集合,而不是手动添加行。
Although this does not work for me since I am binding the DataGrid.ItemsSource
to a collection and not manually adding in the rows.
推荐答案
你可以在XAML中在DataGridRow的资源部分添加默认样式,并在其上声明事件设置器:
You can do that in XAML by adding default style for DataGridRow under its resources section and declare event setter over there:
<DataGrid>
<DataGrid.Resources>
<Style TargetType="DataGridRow">
<EventSetter Event="MouseDoubleClick" Handler="Row_DoubleClick"/>
</Style>
</DataGrid.Resources>
</DataGrid>
OR
如果想在代码背后做到这一点。在网格上设置 x:Name
,以编程方式创建样式,并将样式设置为RowStyle。
In case want to do it in code behind. Set x:Name
on grid, create style programatically and set the style as RowStyle.
<DataGrid x:Name="dataGrid"/>
并在代码中:
Style rowStyle = new Style(typeof(DataGridRow));
rowStyle.Setters.Add(new EventSetter(DataGridRow.MouseDoubleClickEvent,
new MouseButtonEventHandler(Row_DoubleClick)));
dataGrid.RowStyle = rowStyle;
AND
有事件处理程序的例子:
There is example of event handler:
private void Row_DoubleClick(object sender, MouseButtonEventArgs e)
{
DataGridRow row = sender as DataGridRow;
// Some operations with this row
}
这篇关于以编程方式WPF DataGrid行双击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!