WPF TabControl SelectionChanged 重复执行的问题
很邪门的问题,我曾经都感觉是微软的bug了。
问题是这样的:在我的tabcontrol下的tabitem中有一个combobox控件,由于一些原因,需要执行tabcontrol的SelectionChanged 事件,但是比较奇怪的时候,每当我在combobox选择一项时,即combobox的SelectionChanged 事件改变的时候,tabcontrol的SelectionChanged 事件同时也执行了,百思不得其解,后来在网上找到了相关的原因,如下:
This is because of RoutedEvents.To solve it either handle the SelectionChanged of the combobox.
In the function handler of the SelectionChanged for combobox just give e.Handled=true;
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) |
{ |
e.Handled = true; |
} |
if u dont want to do this get the OriginalSource property of SelectionChangedEventArgs in the tabcontrol SelectionChanged handler.This will show whether it is from tabControl or combobox.
大概就是说微软默认事件是可以传递的,如果不想如此传递,就设置e.Handled=true终止传递。
嗯,最后的解决方案就只能在combobox的SelectionChanged事件中设置e.Handled=true了,另外,不止是combobox,同时也包括 listbox,listview,datagrid等存在SelectionChanged 事件的控件。
:注意 ,以上这个是一种解决方案,但是要注意,因为mvvm中事件也是通过传递的方式获取的,这种方式如果是在mvvm中就会出现问题
像如下这种情况:

<i:Interaction.Triggers> <i:EventTrigger EventName="SelectionChanged"> <command:EventToCommand Command="{Binding SelectTestCommand}" /> </i:EventTrigger> </i:Interaction.Triggers>
这种情况下如果你设置e.Handled=true就会使得mvvm中本身的事件也执行不了的,那么在mvvm中这种应该怎么处理呢,那么就只能在tabcontrol的SelectionChanged事件中来设置,具体如下:

<TabControl SelectionChanged="TabControl_OnSelectionChanged"> <i:Interaction.Triggers> <i:EventTrigger EventName="SelectionChanged"> <command:EventToCommand Command="{Binding TabSelectTestCommand}" /> </i:EventTrigger> </i:Interaction.Triggers> <TabItem Header="dd"></TabItem> </TabControl> private void TabControl_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.Source.GetType() != typeof (TabControl)) { e.Handled = true; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义