I added a datagrid in a wpf application.
<DataGrid ItemsSource="{Binding Projects}" SelectedItem="{Binding SelectedProject}" MouseDoubleClick="DataGrid_MouseDoubleClick" />
and here is my code behind
private void DataGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if selected row is header
then do this
else
do this
}
Now question is how I came to know which one is double clicked. It is header or a row. How I can find it out.
Instead of adding double click event in DataGrid, add sperate event for DataGridRow and DataGridColumnHeader. Updated 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>
And here is code behind.
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.
}
You can use 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With