WPF DataGrid column header mouse events RRS feed

  • Question

  • I'm trying to extend standard `DataGrid` functionality by adding some methods and properties into a derived control:
    public class ExtendedGrid : DataGrid	
    But handling mouse events of the headers is still unclear to me. Since DataGridColumnHeader is not a part of the visual tree (correct me if I mistake), and the only way to set an event handler to the `MouseEvent` is to apply style on it (https://stackoverflow.com/questions/5895803/how-do-i-capture-click-events-on-a-datagrid-column-headers).

    Since I'm extending the DataGrid, I'd like to keep implementation in code, without adding any XAML, in my opiinion it's inconsistent in terms of code readability. Therefore, I wrote the following code: 

    private void InitializeStyles()	
    	Style headerStyle = new Style(typeof(DataGridColumnHeader));									 
    	headerStyle.Setters.Add(new EventSetter(MouseDownEvent, new MouseButtonEventHandler(OnColumnHeaderMouseDown)));			 
    	foreach(var column in Columns)
    		column.HeaderStyle = headerStyle;

    This code is called on AutoGeneratedColumns and doesn't work well (e.g. at all). Even if it would, it would impose limitations on setting styles on headers.

    Is there a way to handle DataGridColumnHeader mouse events in my ExtendedGrid without any XAML? Or XAML styles is anyway better than search of workarounds (and probably overcomplicationg things)?

    • Moved by CoolDadTx Thursday, June 25, 2020 1:35 PM WPF related
    Thursday, June 25, 2020 11:35 AM

All replies

  • It is where you can get help.


    Thursday, June 25, 2020 1:11 PM