开发者

RadioButton IsChecked loses binding

开发者 https://www.devze.com 2023-01-26 17:09 出处:网络
I\'m triying to bind to a RadioButton.IsChecked property, and it only works once. After that, the binding doesn\'t work anyore, and I have no idea why this happens. Can anyone help out with this? Than

I'm triying to bind to a RadioButton.IsChecked property, and it only works once. After that, the binding doesn't work anyore, and I have no idea why this happens. Can anyone help out with this? Thanks!

This is my code.

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>


It's an unfortunate known bug. I'm assuming this has been fixed in WPF 4.0 given the new DependencyObject.SetCurrentValue API, but have not verified.


Here is a working solution: http://pstaev.blogspot.com/2008/10/binding-ischecked-property-of.html. It's a shame that Microsoft didn't correct this error.


Just a follow-up to Kent's answer here...this has in fact been fixed in WPF 4.0., I'm leveraging this behavior in my current project. The radio button that is de-activated now gets its binding value set to false, rather than breaking the binding.


I guess you need to implement the INotifyPropertyChanged interface

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

:)

0

精彩评论

暂无评论...
验证码 换一张
取 消