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"/>
  • 相关阅读:
    Appium安装教程
    方法(method)和函数(function)有什么区别?
    FTP两种工作模式:主动模式(Active FTP)和被动模式介绍
    python socket编程介绍
    面向对象基础篇
    python fishc.homework2
    python遇到的问题汇总
    我对 python 面向对象的理解
    深入理解JVM(五)JVM优化策略
    深入理解JVM(四)JVM性能监控与故障处理工具
  • 原文地址:https://www.cnblogs.com/djangochina/p/3491363.html
Copyright © 2011-2022 走看看