代码之家  ›  专栏  ›  技术社区  ›  Carlo

RadioButton IsChecked丢失绑定

  •  6
  • Carlo  · 技术社区  · 14 年前

    我正在triying绑定到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 回复  |  直到 9 年前
        1
  •  5
  •   Tim Cooper    13 年前

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

        2
  •  1
  •   torpederos    11 年前

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

        3
  •  1
  •   karfus    9 年前

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

        4
  •  0
  •   giotto    14 年前

    我想您需要实现inotifyPropertiesChanged接口

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

    :)