Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# WPF uncheck checkboxes

Tags:

c#

wpf

I use MS Visual 2013 Express, C#, and WPF.

In my program there are six checkboxes, and when one of them is checked, the other five should get unchecked.

I googled the last two hours, but can't find a solution as a beginner in C#. In java, i would just write checkbox1.setSelected(false);

I added a clickevent, a checked and unchecked evet in the C# code. I added Checked and Unchecked in the .xaml, but I don't know hot to get it to work.

Hope you can help me :)

=======================

My solution:

Thank you for your help. I tried some random stuff with "IsChecked" you suggested and get it to work luckily.

.Xaml looks like:

            <CheckBox x:Name="CheckBox1" ... Checked="CheckBox1_Checked"  />
            <CheckBox x:Name="CheckBox2" ... Checked="CheckBox2_Checked"  />
            <CheckBox x:Name="CheckBox3" ... Checked="CheckBox3_Checked"  />
            <CheckBox x:Name="CheckBox4" ... Checked="CheckBox4_Checked"  />
            <CheckBox x:Name="CheckBox5" ... Checked="CheckBox5_Checked"  />
            <CheckBox x:Name="CheckBox6" ... Checked="CheckBox6_Checked"  />

C# code for CheckBox1:

    private void CheckBox1_Checked(object sender, RoutedEventArgs e)
    {
        CheckBox1.IsChecked = true;
        CheckBox2.IsChecked = false;
        CheckBox3.IsChecked = false;
        CheckBox4.IsChecked = false;
        CheckBox5.IsChecked = false;
        CheckBox6.IsChecked = false;
    }

e.g. for CheckBox2:

    private void CheckBox2_Checked(object sender, RoutedEventArgs e)
    {
        CheckBox2.IsChecked = true;
        CheckBox1.IsChecked = false;
        CheckBox3.IsChecked = false;
        CheckBox4.IsChecked = false;
        CheckBox5.IsChecked = false;
        CheckBox6.IsChecked = false;
    }

So in the end, it is a very easy task to do.

like image 849
StefanS Avatar asked Jan 09 '23 12:01

StefanS


1 Answers

checkbox1.IsChecked = false;

ToggleButton.IsChecked Property

I am reading it as one special that unchecks the other 5.
If you want to have just one checked at a time then RadioButton would do that.
By default you can't uncheck a RadioButton.
This would allow for all 6 unchecked.

I think binding is better and implement INotifyPropertyChanged

private Bool cbSecial = false;
private Bool cb1 = false;
private Bool cb2 = false;
public Bool CbSpecial 
{
   get { return cbSecial; }
   set 
   {
      if (value == cbSecial) return;
      cbSecial = value;
      if (cbSpecial) 
      {
          Cb1 = false;
          Cb2 = false;
          ... 
      }
      NotifyPropertyChanged("CbSpecial");
   }
}
public Bool Cb1 
{
   get { return cb1; }
   set 
   {
      if (value == cb1) return;
      cb1 = value;
      NotifyPropertyChanged("Cb1 ");
   }
}
like image 82
paparazzo Avatar answered Jan 21 '23 08:01

paparazzo