zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    如何设置IIS程序池的回收时间,才能最大程度的减少对用户的影响?
    C#实现执行数据库事务案例
    RGB色彩对照表
    C# list.ForEach用法
    C# 实现list=list.OrderBy(q=>q.字段名).ToList(); 按多个字段排序
    IIS 7如何实现http重定向https
    Windows 2008 R2上配置IIS7或IIS7.5中的URLRewrite(URL重写)实例
    MVC网站发布到 IIS
    完美解决IE(IE6/IE7/IE8)不兼容HTML5标签的方法
    js返回上一页的实现方法
  • 原文地址:https://www.cnblogs.com/sczmzx/p/4780443.html
Copyright © 2011-2022 走看看