在 C# WPF 中,为什么我的 TabControl 的 SelectionChanged 事件触发过于频繁?
我有一个选项卡式 GUI,每个选项卡都包含一个框架。在这些框架之一中有一个数据网格。当用户选择此选项卡时,我需要对数据网格进行排序,因此我使用 TabControl SelectionChanged 事件来触发排序。然而,每次从 DataGrid 选择一个项目时,即使选项卡本身保持不变,也会触发此事件。
我尝试过许多不同的事件: TabItem 的 GotFocus RequestBringIntoView for a TabItem
但他们似乎都遇到了这个问题。是什么原因造成的?
I have a tabbed GUI with each tab containing a Frame. In one of these Frames there is a DataGrid. When the user selects this tab, I need my datagrid sorted, so I'm using the TabControl SelectionChanged event to trigger the sort. However, this event triggers every time an item is selected from the DataGrid, even though the tabs themselves remain untouched.
I've tried number of different events:
GotFocus for a TabItem
RequestBringIntoView for a TabItem
but they all seem to suffer from this problem. What is causing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
TabControl.SelectionChanged
与ComboBox.SelectionChanged
是相同的事件,它源自
Selector.SelectionChanged
。因此,如果您没有在事件处理程序中将事件标记为已处理,它将在树中向上冒泡,并最终到达您的
TabControl
,这会导致“触发过于频繁”的问题。将您的事件标记为在您的
ComboBox
/ListBox
/ListView
/您在 DataGrid 中使用的任何其他选择器的 SelectionChanged 中进行处理,如下所示:不便将会消失;)。
The
TabControl.SelectionChanged
is the same event as aComboBox.SelectionChanged
It originates from
Selector.SelectionChanged
.So, if you do not mark your event as handled in your event handler, it will bubble up the tree, and eventually arrive at your
TabControl
, which is causing this "firing too often" issue.Mark your event as handled in your SelectionChanged of your
ComboBox
/ListBox
/ListView
/any other Selector you use in your DataGrid like so:And this inconvenience will go away ;).
如果您在父元素中使用 AddHandler 添加了处理程序,则所有选择更改都将触发 SelectionChanged 事件。在这种情况下,您可以为 TabControl 指定一个名称,然后在 EventHandler 中检查 OriginalSource 的名称是否是 TabControl 的名称。
If you have added a handler with AddHandler in a parent element, all selection changes will fire the SelectionChanged-event. In this case, you can give your TabControl a name and then check in the EventHandler if the name of the OriginalSource is the name of your TabControl.
另一个好的方法是向 tabControl.Items.SelectionChanged 添加一个处理程序:
也许不是 xamly 方式,但不会那么痛苦,因为它仅在项目更改时触发。
Another good approch is adding a handler to the tabControl.Items.SelectionChanged:
Maybe is not the xamly way, but is less pain as it only fires when an item is changed.