附加事件?如何在运行时删除 WPF DataGrid 的 ScrollChanged 事件处理程序
WPF 数据网格 类(不是 Windows 窗体 DataGrid!)可以设置为自动处理滚动,无需外部 ScrollViewer,并且可以为控件的内部滚动条注册事件处理程序通过这样编写 XAML:
<DataGrid ScrollViewer.ScrollChanged="dGrid_ScrollChanged" />
如果我错了,请纠正我,但在这种情况下,内部 ScrollViewer 似乎是某种未记录的附加属性。 ScrollViewer 不是 DataGrid 的公共字段,您在 DataGrid 文档中找不到对 ScrollViewer 或 ScrollChanged 事件的引用。换句话说,简单地执行 myDataGrid.ScrollViewer.ScrollChanged += dGrid_ScrollChanged
是行不通的。
所以我的问题是,如何在运行时添加或删除此 ScrollChanged 事件的事件处理程序?我试图理解这里发生的事情,就像我试图解决问题一样,所以解释越多越好。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试在后面的代码中像这样使用UIElement的AddHandler和RemoveHandler -
由于ScrollViewer不是dataGrid的依赖属性,因此您需要使用AddHandler进行挂钩。就像你不能像这样简单地设置 Grid.RowSpan
dg.Grid.RowSpan = 2
您必须设置附加属性,例如
dg.SetValue(Grid.RowSpanProperty, 2)
您需要挂钩附加属性的事件也是如此。
Try using UIElement's AddHandler and RemoveHandler like this in your code behind -
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.
您可以使用 UIElement.RemoveHandler 方法。
如果您的网格有一个名称:“grid”,那么您可以这样做:
ScrollViewer.ScrollChanged
不是 DataGrid 的属性,但它是您可以在使用 ScrollViewerYou can use UIElement.RemoveHandler method.
if your grid has a name: "grid" then you can do it like this:
The
ScrollViewer.ScrollChanged
is not a property of DataGrid, but it's attached property that you can use on FrameworkElements that use ScrollViewer