测试代码下载: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"/>