zoukankan      html  css  js  c++  java
  • wpf RadioButton控件的一个bug,onpropertychanged后会修改旧属性的值

    测试代码下载:http://files.cnblogs.com/djangochina/RadioButtonBug.zip

    从上面列表选择不同的行,再设置下面不同的radiobutton看看结果

    bug情况简单描述如下

    一个列表控件listbox、listview或者datagrid,绑定如下

    SelectedItem="{Binding SelectedData}"

    当然这个SelectedData是一个实现了INotifyPropertyChanged的实体。比如说是Person,里面有 IsMan和IsWoman两个bool

    绑定到两个RadionButton

    <RadioButton IsChecked="{Binding IsMan}" Content="Man"/>
                                            <RadioButton IsChecked="{Binding IsWoman}" Content="Woman"/>

    当来回切换列表控件的选中项的时候会发现这两个RadioButton的值会有错误,会修改旧选中项属性的值。

    解决方法

        public class RadioButtonExtended : RadioButton
        {
            public static readonly DependencyProperty IsCheckedExtProperty =
                DependencyProperty.Register("IsCheckedExt", typeof(bool?), typeof(RadioButtonExtended),
                                            new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Journal | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, IsCheckedRealChanged));
    
            private static bool _isChanging;
    
            public RadioButtonExtended()
            {
                Checked += RadioButtonExtendedChecked;
                Unchecked += RadioButtonExtendedUnchecked;
            }
    
            public bool? IsCheckedExt
            {
                get
                {
                    return (bool?)GetValue(IsCheckedExtProperty);
                }
                set
                {
                    SetValue(IsCheckedExtProperty, value);
                }
            }
    
            public static void IsCheckedRealChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                _isChanging = true;
                ((RadioButtonExtended)d).IsChecked = (bool)e.NewValue;
                _isChanging = false;
            }
    
            private void RadioButtonExtendedChecked(object sender, RoutedEventArgs e)
            {
                if (!_isChanging)
                    IsCheckedExt = true;
            }
    
            private void RadioButtonExtendedUnchecked(object sender, RoutedEventArgs e)
            {
                if (!_isChanging)
                    IsCheckedExt = false;
            }
        }

    使用

    <controls:RadioButtonExtended GroupName="Sex" IsCheckedExt="{Binding IsMan}" Content="Man"/>
    <controls:RadioButtonExtended GroupName="Sex" IsCheckedExt="{Binding IsWoman}" Content="Woman"/>
  • 相关阅读:
    razor在App_Code中使用ActionLink无效的解决方案
    科技的进步会给人带来幸福么?
    C6000系列之C6455 DSP的EMIFA接口
    C6000系列之C6455DSP的GPIO模块
    C语言文件操作与例子
    C语言中fscanf函数读取double型浮点数的问题
    MATLAB读取CCS保存的数据
    CCS 3.3 操作C函数读写文件
    复数矩阵乘法C语言实现
    C6000系列之C6455DSP的中断系统
  • 原文地址:https://www.cnblogs.com/djangochina/p/3491363.html
Copyright © 2011-2022 走看看