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>
View Code

这种情况下如果你设置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;
            }
        }
View Code

 

转载于:https://www.cnblogs.com/sczmzx/p/4780443.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值