Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind Xaml Radio button to boolean

Tags:

wpf

xaml

I saw many posts on how to bind a boolean value to a radio button. But my scenario is that I need to bind it to a radio button and read the selection from the user.

That is no option should be selected intially.

If I bind it to a boolean, since boolean cant be null it shows the default value selected in radio button.

If I use nullable boolean, I still defaults to false when trying to use the converter.

I cant use oneway mode in xaml as I need to check if the radio button selection was made which I do using the bounded variable.

Ant pointers on how to achieve this?

like image 335
ashish g Avatar asked Aug 26 '13 17:08

ashish g


1 Answers

You can bind a nullable boolean to your radio buttons, but you need to do it through a converter.

First declare your variable:

private bool? answer;
public bool? Answer
{
    get { return answer; }
    set
    {
        answer = value;
        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Answer"));
    }
}

and initialise it to null.

Then in the XAML:

<Window.Resources>
    <local:BooleanConverter x:Key="BooleanConverter"/>
</Window.Resources>

<StackPanel Grid.Row="1">
    <RadioButton Content="I Agree"
                 IsChecked="{Binding Answer,
                             Converter={StaticResource BooleanConverter},
                             ConverterParameter='true', Mode=TwoWay}" />
    <RadioButton Content="I Disagree"
                 IsChecked="{Binding Answer,
                             Converter={StaticResource BooleanConverter},
                             ConverterParameter='false', Mode=TwoWay}" />
</StackPanel>

And finally your converter:

class BooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var test = (bool?)value;
        var result = bool.Parse((string)parameter);

        if (test == result)
        {
            return true;
        }

        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var result = bool.Parse((string)parameter);
        return result;
    }
}

This binds the radio button to Answer and states that the first one will only be checked when the value is true and the second one will be checked when the answer is false. You can then check that Answer is not null before letting the user proceed.

like image 118
ChrisF Avatar answered Nov 19 '22 21:11

ChrisF