Handling DataGrid column header right mouse button click

Nov 26, 2008 at 9:51 AM
I am working on a project that uses the new DataGrid WPF control to display and allow the user to edit various tables. Previously, I have used the combination of ListView and GridView that allows me to handle column header right-button clicks differently from right-button clicks in the content area, which works very well in the scenario I am developing for. However, I cannot seem to find a way to do the same thing with the V1 DataGrid. Even simply setting the column header context menu differently from that of the content area (as is done in e.g. the Windows XP and Windows 2008 "Windows Explorer" details view) would do very well.

Has anyone managed to do something like this and if so, how? An example XAML snippet would be great, but pointers in the right direction could be a good start. I would prefer to not have to dig too deeply into the DataGrid source code.
Nov 26, 2008 at 10:53 AM
Hi,

How about the following:

Handle the mouse event for your DataGrid

<dg:DataGrid Name="dataGrid"  ... MouseRightButtonUp="dataGrid_MouseRightButtonUp">

This event will tunnel (or is it bubble?!!) from the clicked element to your DataGrid. The e.OriginalSource will be the element that was clicked on. You can then navigate the visual tree to see if this item is within a cell or the column header.

private void dataGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    DependencyObject dep = (DependencyObject)e.OriginalSource;

    while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
    {
        dep = VisualTreeHelper.GetParent(dep);
    }

    if (dep == null)
        return;

    if (dep is DataGridColumnHeader)
    {
        // do something
    }

    if (dep is DataGridCell)
    {
        // do something else - possibly navigate to the row.
    }
}

Hope that helps,
Colin E.
Nov 26, 2008 at 1:58 PM
Yes, this works great! I was hoping for something doable purely in XAML but it is definitely good enough unless someone else comes up with something.

Many thanks, Colin.
Nov 26, 2008 at 2:08 PM
Hi,

Glad it worked :-) I would not get too hung about about doing everything in XAML. I know that doing everything in XAML makes you look like a super-cool WPF coder, but really it does not make sense for everything.

I am pretty sure that what you are asking is not possible in pure - XAML.

Colin E.