Reputation: 1880
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.
Upvotes: 4
Views: 3722
Reputation: 81313
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.
Upvotes: 7
Reputation: 4918
You can use UIElement.RemoveHandler method.
if your grid has a name: "grid" then you can do it like this:
grid.RemoveHandler(ScrollViewer.ScrollChangedEvent, new ScrollChangedEventHandler(dGrid_ScrollChanged));
The ScrollViewer.ScrollChanged
is not a property of DataGrid, but it's attached property that you can use on FrameworkElements that use ScrollViewer
Upvotes: 0