简体   繁体   中英

checkbox event not firing when unchecked

Simple question over here. Pretty simple code too.

I have a checkbox and I also have a combobox.

Basically the combobox's selected item should change whenever the the checkbox is ticked or unticked.That's not going so well right now.

It works when it's going from uncheked to checked, but when I uncheck it, the combobox value stays the same.

Checkbox Code:

private void linked_Checked(object sender, RoutedEventArgs e)
    {
        if (linked.IsChecked == true)
        {
            Chained.SelectedIndex = 0;
        }

        if (linked.IsChecked == false)
        {
            Chained.SelectedIndex = 1;
        }
    }

Combobox Code:

<ComboBox x:Name="Chained"  Text="{Binding Chained, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="128,69,132,-92" Grid.Row="15" Visibility="Visible" SelectionChanged="Chained_SelectionChanged" >
                    <ComboBoxItem Content="True"/>
                    <ComboBoxItem Content="False"/>
                </ComboBox>

This should be pretty straight forward right? So where am I going wrong? If there's a way to do this in xaml then I'm all ears too.

Put it inside Unchecked event,

private void linked_UnChecked(object sender, RoutedEventArgs e)
    { 
        if (linked.IsChecked == false)
        {
            Chained.SelectedIndex = 1;
        }
    }

The reason is when the checked event is fired, the state is not changed yet and this happends before the new value get set. It means when the event is fired you are still getting the old value. So I always find CheckStateChanged event much better . Because this event is fired when the check state is changes. so then you can say something like this.

  private void checkBox1_CheckStateChanged(object sender, EventArgs e)
            {

               if (linked.CheckState == CheckState.Checked){

                Chained.SelectedIndex = 0;
               }


            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM