当前位置:首页 > Windows程序 > 正文

WPF TabControl SelectionChanged 重复执行的问题

2021-03-26 Windows程序

很邪门的问题,我曾经都感觉是微软的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 事件的控件。

WPF TabControl SelectionChanged 重复执行的问题

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/67747.html