我终于找到了答案:
如果您尝试在 WPF 中将 RadioButton 的 IsChecked 属性绑定到对象,您很可能遇到以下问题:在 OneWay 绑定中效果很好。但是,如果您有多个 RadioButtons 绑定了 TwoWay,并且您单击了一个未选中的 RadioButton,那么您期望先前选中的 RadioButton 绑定到的对象接收 False 值。但是你的期望是错误的。这是因为由于某些原因,Microsoft 不遵守绑定并且不将 False 值传递给 DependencyProperty,而是直接将值 False 分配给属性,这会破坏绑定。
互联网上有很多解决方案,但问题在于它们不适用于动态生成的控件。因此,由于我必须找到一种方法来使其与动态控件一起工作,因此决定制作一个真正的 RadioButton 的包装器,它将以两种方式正确绑定。这是包装器的代码:
using System;
using System.IO;
using System.Printing;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using Microsoft.Win32;
namespace Controls
{
public class RadioButtonExtended : RadioButton
{
static bool m_bIsChanging = false;
public RadioButtonExtended()
{
this.Checked += new RoutedEventHandler(RadioButtonExtended_Checked);
this.Unchecked += new RoutedEventHandler(RadioButtonExtended_Unchecked);
}
void RadioButtonExtended_Unchecked(object sender, RoutedEventArgs e)
{
if (!m_bIsChanging)
this.IsCheckedReal = false;
}
void RadioButtonExtended_Checked(object sender, RoutedEventArgs e)
{
if (!m_bIsChanging)
this.IsCheckedReal = true;
}
public bool? IsCheckedReal
{
get { return (bool?)GetValue(IsCheckedRealProperty); }
set
{
SetValue(IsCheckedRealProperty, value);
}
}
// Using a DependencyProperty as the backing store for IsCheckedReal. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsCheckedRealProperty =
DependencyProperty.Register("IsCheckedReal", typeof(bool?), typeof(RadioButtonExtended),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Journal |
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
IsCheckedRealChanged));
public static void IsCheckedRealChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
m_bIsChanging = true;
((RadioButtonExtended)d).IsChecked = (bool)e.NewValue;
m_bIsChanging = false;
}
}
}
所以现在您所要做的就是使用 ExtendedRadioButton 而不是内置按钮,并绑定到 IsCheckedReal 属性而不是 IsChecked 属性。
享受?