Search code examples
c#wpfradio-button

How to Uncheck radio button in WPF (MVVM)


I have a radio buttons group. The choice is not mandatory to fill the form. At the beginning all the radio buttons are unchecked. If the user unintentionally clicks on one of them, he can not go back, because at least one has to be checked.

So How can I uncheck a radio button and not force the user to make an unwanted choice?

p.s. the form is built at run-time and I am following the MVVM design pattern. For Mandatory choices, the radio buttons solution fit very well and I already use it in this case.


Solution

  • Personally when I want this behavior I use a ListBox with the Template overwritten to use RadioButtons.

    It's the best control suited to do all of the following :

    • display a list of items
    • only one item can be selected at a time, so only one property maintained in data model
    • user can leave selected item as null, indicating no item is selected

    My custom style for the ListBox removes the borders and background color, and draws each item using a RadioButton with the IsChecked bound to the ListBoxItem.IsSelected. Typically something like this :

    <Style x:Key="RadioButtonListBoxStyle" TargetType="{x:Type ListBox}">
        <Setter Property="BorderBrush" Value="Transparent"/>
        <Setter Property="KeyboardNavigation.DirectionalNavigation" Value="Cycle" />
        <Setter Property="ItemContainerStyle">
            <Setter.Value>
                <Style TargetType="{x:Type ListBoxItem}" >
                    <Setter Property="Margin" Value="2, 2, 2, 0" />
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate>
                                <Border Background="Transparent">
                                    <RadioButton
                                        Content="{TemplateBinding ContentPresenter.Content}" VerticalAlignment="Center"
                                        IsChecked="{Binding Path=IsSelected,RelativeSource={RelativeSource TemplatedParent},Mode=TwoWay}"/>
                                </Border>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </Setter.Value>
        </Setter>
    </Style>
    

    And to display the RadioButtons themselves is usually something very simple, like this :

    <ListBox ItemsSource="{Binding AvailableValues}"
             SelectedValue="{Binding SelectedValue}"
             Style="{StaticResource RadioButtonListBoxStyle}" />