单选按钮的IsChecked属性失去了绑定。

7

我正在尝试绑定到一个 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个回答

5

1
啊,那太糟糕了。我想我只能回到事件处理程序了...你知道除此之外还有什么解决方法吗? - Carlo
使用 ListBox 并将每个 ListBoxItem 样式设置为类似于 RadioButton 的外观。http://code.msdn.microsoft.com/wpfradiobuttonlist - Kent Boogaart

1

1
这是对Kent在此处的回答的跟进...这实际上已经在WPF 4.0中修复了,我正在我的当前项目中利用这种行为。现在,被停用的单选按钮会将其绑定值设置为false,而不是破坏绑定。

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...

:)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接