RadioButton IsChecked失去了约束力

时间:2010-11-21 00:21:55

标签: wpf binding

我正在试图绑定到RadioButton.IsChecked属性,它只能工作一次。在那之后,绑定不起作用,我不知道为什么会发生这种情况。任何人都可以帮忙吗?谢谢!

这是我的代码。

C#

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        this.DataContext = new ViewModel();
    }
}

public class ViewModel
{
    private bool _isChecked1 = true;
    public bool IsChecked1
    {
        get { return _isChecked1; }
        set
        {
            if (_isChecked1 != value)
            {
                _isChecked1 = value;
            }
        }
    }

    private bool _isChecked2;
    public bool IsChecked2
    {
        get { return _isChecked2; }
        set
        {
            if (_isChecked2 != value)
            {
                _isChecked2 = value;
            }
        }
    }
}

XAML:

<Grid>
    <StackPanel>
        <RadioButton Content="RadioButton1" IsChecked="{Binding IsChecked1}" />
        <RadioButton Content="RadioButton2" IsChecked="{Binding IsChecked2}" />
    </StackPanel>
</Grid>

4 个答案:

答案 0 :(得分:5)

这是一个不幸的known bug。我假设已经在WPF 4.0中修复了新的DependencyObject.SetCurrentValue API,但尚未验证。

答案 1 :(得分:1)

这是一个有效的解决方案:http://pstaev.blogspot.com/2008/10/binding-ischecked-property-of.html。很遗憾微软没有纠正这个错误。

答案 2 :(得分:1)

这里只是肯特答案的后续行动......这实际上已经在WPF 4.0中修复了。我正在当前的项目中利用这种行为。现在,取消激活的单选按钮将其绑定值设置为false,而不是破坏绑定。

答案 3 :(得分:0)

我想你需要实现INotifyPropertyChanged接口

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String info)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(info));
    }
}


private bool _isChecked1 = true;
public bool IsChecked1
{
    get { return _isChecked1; }
    set
    {
        if (_isChecked1 != value)
        {
            _isChecked1 = value;
            NotifyPropertyChanged("IsChecked1");
        }
    }
} // and the other property...

:)