Search code examples
c#wpfwpf-controlswpfdatagridattached-properties

Attached Event? How to remove ScrollChanged event handler for WPF DataGrid at runtime


The WPF DataGrid class (Not the Windows Forms DataGrid!) can be set up to automatically handle scrolling without an external ScrollViewer and it's possible to register an event handler for the control's internal scrollbar by writing XAML like such:

<DataGrid ScrollViewer.ScrollChanged="dGrid_ScrollChanged"  />

Correct me if I'm wrong but in this case, the internal ScrollViewer appears to be some kind of undocumented attached property. ScrollViewer is not a public field of DataGrid and you will find no reference to either ScrollViewer or the ScrollChanged event in the DataGrid documentation. In other words simply doing myDataGrid.ScrollViewer.ScrollChanged += dGrid_ScrollChanged doesn't work.

So my question is, how does one go about adding or removing an event handler for this ScrollChanged event at runtime? I'm trying to understand what's going on here as much as I'm trying to solve the problem so the more explanation the better.


Solution

  • Try using UIElement's AddHandler and RemoveHandler like this in your code behind -

    dg.AddHandler(ScrollViewer.ScrollChangedEvent, new ScrollChangedEventHandler(dg_ScrollChanged));
    dg.RemoveHandler(ScrollViewer.ScrollChangedEvent, new ScrollChangedEventHandler(dg_ScrollChanged));
    

    Since ScrollViewer is not a Dependency Property of your dataGrid, you need to hook using AddHandler. Just like you can't set Grid.RowSpan simply like this dg.Grid.RowSpan = 2 You have to set Attach Properties like dg.SetValue(Grid.RowSpanProperty, 2) Same goes with events you need to hook for attached properties.