WPF DataGrid column header mouse events

Arli Chokoev 1 Reputation point
2020-06-29T06:23:36.72+00:00

I have following events with subscriptions in the class, derived from DataGrid:

private void SubscribeHeaders(DependencyObject sender = null)
{
    sender = sender ?? this;

    for (int childIndex = 0; childIndex < VisualTreeHelper.GetChildrenCount(sender); childIndex++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(sender, childIndex);
        if (child is DataGridColumnHeader colHeader)
        {
            //Subscribe column headers
            colHeader.PreviewMouseLeftButtonDown += (obj, e) => OnColumnHeaderMouseDown(obj, e);
            colHeader.PreviewMouseLeftButtonUp += (obj, e) => OnColumnHeaderMouseUp(obj, e);
            colHeader.MouseEnter += (obj, e) => OnColumnHeaderMouseEnter(obj, e);
            colHeader.MouseLeave += (obj, e) => OnColumnHeaderMouseLeave(obj, e);

        }
        else if (child is DataGridRowHeader rowHeader)
        {
            //Subscribe row headers
        }
        else
        {
            SubscribeHeaders(child);
        }
    }
}

Everything binds fine, but OnColumnHeaderMouseEnter(obj, e) is not executed, while mouse button is pressed. It doesn't seem like mouse is captured,

if (Mouse.Captured != null)
    Mouse.Captured.ReleaseMouseCapture();

does not change anything, since Mouse.Captured is always null.

What I'm trying to achieve is to select a range of DataGrid columns by dragging a mouse with a pressed left button from start to the end of selection. My idea is to react on mouse buttons and movements from header to header.

How can I capture movements between DataGridColumnHeaders with a mouse button pressed?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,688 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. DaisyTian-1203 11,616 Reputation points
    2020-06-29T08:41:13.04+00:00

    I will give you a workaround with getting the selection by event SelectedCellsChanged.
    1.Make the DataGrid with the below setting:

    SelectedCellsChanged="Dg_SelectedCellsChanged" SelectionMode="Extended" SelectionUnit="CellOrRowHeader" 
    

    2.Then get the each selectedCell like this:

     private void Dg_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
            {
                foreach (DataGridCellInfo info in dataGrid.SelectedCells)
                {
                    FrameworkElement element = info.Column.GetCellContent(info.Item);
                    string str = ((TextBlock)info.Column.GetCellContent(info.Item)).Text;
                    Console.WriteLine(str);
                }
            }
    
    0 comments No comments