Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find either header or row is double clicked on datagrid wpf

Tags:

c#

wpf

datagrid

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.

like image 215
fhnaseer Avatar asked Oct 25 '25 08:10

fhnaseer


2 Answers

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.
}
like image 114
fhnaseer Avatar answered Oct 26 '25 21:10

fhnaseer


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
}
like image 33
Vale Avatar answered Oct 26 '25 21:10

Vale