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"/>
  • 相关阅读:
    查看线程
    shiro+多tomcat+redis实现session共享
    win11系统设置笔记本合盖上不休眠
    nvm切换node版本出现乱码 exit status 1:
    nvm安装vuecli
    SQL Server Management 2012 启动错误及解决:Cannot find one or more componets
    SQL Server 2012 连接 Oracle 11gR2 Database
    SQL Server 数据库跨区域时间问题
    SSIS 同步不同数据库的不同两张表
    Reporting Service 不能发送订阅报表的问题
  • 原文地址:https://www.cnblogs.com/djangochina/p/3491363.html
Copyright © 2011-2022 走看看