How to uncheck a switch in WPF (MVVM)

I have a group of radio buttons. The selection is not required to fill out the form. At first, all switches are not checked. If the user inadvertently clicks on one of them, he cannot return, because at least one needs to be checked.

So, how to uncheck the switch and not force the user to make an unwanted choice?

ps the form is created at runtime, and I follow the MVVM design pattern. For mandatory elections, the radio button solution fits very well, and I already use it in this case.

+8
source share
11 answers

, , ListBox , RadioButtons.

, :

  • ,
  • , ,

ListBox , , RadioButton IsChecked, ListBoxItem.IsSelected. , - :

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

RadioButton-, , :

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

:

public class OptionalRadioButton : RadioButton
{
    #region bool IsOptional dependency property
    public static DependencyProperty IsOptionalProperty = 
        DependencyProperty.Register(
            "IsOptional", 
            typeof(bool), 
            typeof(OptionalRadioButton), 
            new PropertyMetadata((bool)true,
                (obj, args) =>
                {
                    ((OptionalRadioButton)obj).OnIsOptionalChanged(args);
                }));
    public bool IsOptional
    {
        get
        {
            return (bool)GetValue(IsOptionalProperty);
        }
        set
        {
            SetValue(IsOptionalProperty, value);
        }
    }
    private void OnIsOptionalChanged(DependencyPropertyChangedEventArgs args)
    {
        // TODO: Add event handler if needed
    }
    #endregion

    protected override void OnClick()
    {
        bool? wasChecked = this.IsChecked;
        base.OnClick();
        if ( this.IsOptional && wasChecked == true )
            this.IsChecked = false;
    }
}
+10

Eventhandlers

<RadioButton Checked="RB_Checked" Click="RB_Clicked"/>

Codebehind XAML:

Private JustChecked as Boolean

Private Sub RB_Checked(sender As Object, e As RoutedEventArgs)
    Dim s As RadioButton = sender
    ' Action on Check...
    JustChecked = True
End Sub

Private Sub RB_Clicked(sender As Object, e As RoutedEventArgs)
    If JustChecked Then
        JustChecked = False
        e.Handled = True
        Return
    End If
    Dim s As RadioButton = sender
    If s.IsChecked Then s.IsChecked = False        
End Sub

#

private bool JustChecked;
private void RB_Checked(object sender, RoutedEventArgs e)
{
    RadioButton s = sender;
    // Action on Check...
    JustChecked = true;
}

private void RB_Clicked(object sender, RoutedEventArgs e)
{
    if (JustChecked) {
        JustChecked = false;
        e.Handled = true;
        return;
    }
    RadioButton s = sender;
    if (s.IsChecked)
        s.IsChecked = false;
}

"" " "

+6

:

<RadioButton x:Name="MyRadioButton">Some Radio Button</RadioButton>

:

 MyRadioButton.IsChecked = false;

, :

:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();

        this.DataContext = this;

    }

    #region INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }

    #endregion


    private bool _isRadioChecked;

    public bool IsRadioChecked
    {
        get
        {
            return _isRadioChecked;
        }
        set
        {
            _isRadioChecked = value;
            OnPropertyChanged("IsRadioChecked");
        }
    }
}

xaml ():

<RadioButton IsChecked="{Binding IsRadioChecked}">Some Radio Button</RadioButton>
0

, @Tomtom, , , , , .

.

?

  • Google
0

Tomtom , RadioButton, , , - , - , .

:

  • "" RadioButton
  • RadioButton, , .
  • "", RadioButton

, , , :

   // Create an instance of the control
   var controlType = typeof(Control).Assembly.GetType(fullyQualifiedControl, true);
   var control = Activator.CreateInstance(controlType);

    switch (fullyQualifiedControl)
    {
       case "System.Windows.Controls.RadioButton":
          ((RadioButton)control).Checked += new RoutedEventHandler(DataDrivenControl_Checked);
          ((RadioButton)control).Unchecked += new RoutedEventHandler(DataDrivenControl_UnChecked);
          break;
    }
0

RadioButton

<StackPanel>
    <RadioButton Content="Option 1" GroupName="optionSet1" PreviewMouseDown="RadioButton_OnPreviewMouseDown"/>
    <RadioButton Content="Option 2" GroupName="optionSet1" PreviewMouseDown="RadioButton_OnPreviewMouseDown"/>
    <RadioButton GroupName="optionSet1" x:Name="rbEmpty" Visibility="Collapsed" />
</StackPanel>

RadioButton, RadioButton

private void RadioButton_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        var radioButton = sender as RadioButton;
        if (radioButton.IsChecked.GetValueOrDefault())
        {
            rbEmpty.IsChecked = true;
            e.Handled = true;
        }
    }
0

, , UWP, , . , , :

Xaml:

<Grid>
    <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
        <RadioButton x:Name="RB1" GroupName="RBTest" Content="Item No. 1" Click="RBtn_Click"/>
        <RadioButton x:Name="RB2" GroupName="RBTest" Content="Item No. 2" Click="RBtn_Click"/>
        <RadioButton x:Name="RB3" GroupName="RBTest" Content="Item No. 3" Click="RBtn_Click"/>
        <RadioButton x:Name="RB4" GroupName="RBTest" Content="Item No. 4" Click="RBtn_Click"/>
        <RadioButton x:Name="RB5" GroupName="RBTest" Content="Item No. 5" Click="RBtn_Click"/>
    </StackPanel>
</Grid>

:

public sealed partial class MainPage : Page
{
    private bool rb1PrevState;
    private bool rb2PrevState;
    private bool rb3PrevState;
    private bool rb4PrevState;
    private bool rb5PrevState;

    public MainPage()
    {
        this.InitializeComponent();
        rb1PrevState = this.RB1.IsChecked.Value;
        rb2PrevState = this.RB2.IsChecked.Value;
        rb3PrevState = this.RB3.IsChecked.Value;
        rb4PrevState = this.RB4.IsChecked.Value;
        rb5PrevState = this.RB5.IsChecked.Value;

    }

    private void RBtn_Click(object sender, RoutedEventArgs e)
    {
        RadioButton rbtn = sender as RadioButton;

        if (rbtn != null)
        {
            if (rbtn.IsChecked.Value == true)
            {
                switch (rbtn.Name)
                {
                    case "RB1":
                        if (rb1PrevState == true)
                        {
                            rbtn.IsChecked = false;
                            rb1PrevState = false;
                        }
                        else
                        {
                            rb1PrevState = true;
                            ResetRBPrevStates("RB1");
                        }
                        break;
                    case "RB2":
                        if (rb2PrevState == true)
                        {
                            rbtn.IsChecked = false;
                            rb2PrevState = false;
                        }
                        else
                        {
                            rb2PrevState = true;
                            ResetRBPrevStates("RB2");
                        }
                        break;
                    case "RB3":
                        if (rb3PrevState == true)
                        {
                            rbtn.IsChecked = false;
                            rb3PrevState = false;
                        }
                        else
                        {
                            rb3PrevState = true;
                            ResetRBPrevStates("RB3");
                        }
                        break;
                    case "RB4":
                        if (rb4PrevState == true)
                        {
                            rbtn.IsChecked = false;
                            rb4PrevState = false;
                        }
                        else
                        {
                            rb4PrevState = true;
                            ResetRBPrevStates("RB4");
                        }
                        break;
                    case "RB5":
                        if (rb5PrevState == true)
                        {
                            rbtn.IsChecked = false;
                            rb5PrevState = false;
                        }
                        else
                        {
                            rb5PrevState = true;
                            ResetRBPrevStates("RB5");
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private void ResetRBPrevStates(string _excludeRB)
    {
        rb1PrevState = (_excludeRB == "RB1" ? rb1PrevState : false);
        rb2PrevState = (_excludeRB == "RB2" ? rb2PrevState : false);
        rb3PrevState = (_excludeRB == "RB3" ? rb3PrevState : false);
        rb4PrevState = (_excludeRB == "RB4" ? rb4PrevState : false);
        rb5PrevState = (_excludeRB == "RB5" ? rb5PrevState : false);
    }
}

, , MVVM.

0

, , .

  int click = 0;
    private void RadioButton_Click(object sender, RoutedEventArgs e)
    {
        click++;
        ((RadioButton)sender).IsChecked = click % 2 == 1 ;
        click %= 2;
    }
0

In this case you should not use RadioButton. The purpose of this control is that always one is checked. In your scenario, I would rather useCheckBox

-1
source

A RadioButtoncannot be removed. If you need to continue to use RadioButtons, I would add the option "Not selected" by default. In this case, I prefer ComboBoxwith an empty item or a cleanup button at the top.

-1
source

Source: https://habr.com/ru/post/1608510/


All Articles