• 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"/>
  • 相关阅读:
    Hive2.0函数大全(中文版)
    Centos7 安装并配置redis
    Java内部类
    beeline: 新版连接Hive server的工具
    jsoup的Document类
    Jsoup类
    jsoup的Node类
    jsoup的Element类
    Java中的多线程
    Java中的文件IO流
  • 原文地址:https://www.cnblogs.com/djangochina/p/3491363.html
Copyright © 2020-2023  润新知