我在wpf应用程序中添加了一个datagrid。
<DataGrid ItemsSource="{Binding Projects}" SelectedItem="{Binding SelectedProject}" MouseDoubleClick="DataGrid_MouseDoubleClick" />
这是我的代码
private void DataGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if selected row is header
then do this
else
do this
}
现在的问题是我是如何知道哪一个是双击的。它是标题或行。我怎么能找到它。
答案 0 :(得分:6)
不是在DataGrid中添加双击事件,而是为DataGrid Row和DataGridColumnHeader添加单独的事件。 更新了XAML:
<DataGrid ItemsSource="{Binding Projects}" SelectedItem="{Binding SelectedProject}" MouseDoubleClick="DataGrid_MouseDoubleClick">
<DataGrid.Resources>
<Style TargetType="DataGridRow">
<EventSetter Event="MouseDoubleClick" Handler="DataGridRow_MouseDoubleClick" />
</Style>
</DataGrid.Resources>
<DataGrid.Resources>
<Style TargetType="DataGridColumnHeader">
<EventSetter Event="MouseDoubleClick" Handler="DataGridColumnHeader_MouseDoubleClick" />
</Style>
</DataGrid.Resources>
</DataGrid>
这是背后的代码。
private void DataGridRow_MouseDoubleClick(object sender, System.Windows.RoutedEventArgs e)
{
// This is when a row is double clicked.
}
private void DataGridColumnHeader_MouseDoubleClick(object sender, System.Windows.RoutedEventArgs e)
{
// This is when header is double clicked.
}
答案 1 :(得分:0)
您可以使用VisualTreeHelper:
private void DataGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
var dep = e.OriginalSource as DependencyObject;
//go up the tree until you find the header
while (dep != null && !(dep is DataGridRowHeader)) {
dep = VisualTreeHelper.GetParent(dep);
}
//header found
if (dep is DataGridRowHeader)
//do this
else //header not found
//do that
}