Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RadioButton IsChecked loses binding

Tags:

binding

wpf

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>
like image 836
Carlo Avatar asked Nov 21 '10 00:11

Carlo


2 Answers

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.

like image 150
Kent Boogaart Avatar answered Dec 12 '22 13:12

Kent Boogaart


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.

like image 40
torpederos Avatar answered Dec 12 '22 14:12

torpederos