【问题标题】:RadioButton IsChecked loses bindingRadioButton IsChecked 失去绑定
【发布时间】:2010-11-21 00:21:54
【问题描述】:

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

【问题讨论】:

    标签: wpf binding


    【解决方案1】:

    这是一个不幸的known bug。鉴于新的DependencyObject.SetCurrentValue API,我假设此问题已在 WPF 4.0 中得到修复,但尚未验证。

    【讨论】:

    • 啊,这太可怕了。我想我将不得不回到事件处理程序......你知道除此之外的任何解决方法吗?
    • 使用ListBox 并将每个ListBoxItem 设置为看起来像RadioButtoncode.msdn.microsoft.com/wpfradiobuttonlist
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      只是对 Kent 的回答的跟进……这实际上已在 WPF 4.0 中得到修复。我在当前的项目中利用了这种行为。取消激活的单选按钮现在将其绑定值设置为 false,而不是破坏绑定。

      【讨论】:

        【解决方案4】:

        我猜你需要实现 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...
        

        :)

        【讨论】:

          猜你喜欢
          • 2012-10-23
          • 2011-06-16
          • 1970-01-01
          • 1970-01-01
          • 2018-08-15
          • 2011-08-27
          • 2011-02-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多