What comes first: ToggleButton.IsChecked binding update or Command binding?

First - disclaimer:

If you are reading this because you want to use IsChecked and RelayCommand as bindings to make a difference, you are probably doing it wrong. You must work with the IsChecked Set() binding.

Question:

I have a ToggleButton in which there is both a binding for IsChecked and for Command :

 <ToggleButton IsChecked="{Binding BooleanBackedProperty}" Command="{Binding SomeCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" CommandParameter="{Binding}" /> 

Yes, I know, tsk tsk. Failed to help.

When the user clicks ToggleButton, which of these two will be launched first? Is the command running, or is the IsChecked bundle about to update the bound property? Or - does it really look like a social message in which he creates a race condition ?

+5
source share
1 answer

IsChecked will have a valid value during command execution.

ToggleButton overrides OnClick from ButtonBase as follows:

  protected override void OnClick() { OnToggle(); base.OnClick(); } 

OnToggle is a method that updates IsChecked :

  protected internal virtual void OnToggle() { // If IsChecked == true && IsThreeState == true ---> IsChecked = null // If IsChecked == true && IsThreeState == false ---> IsChecked = false // If IsChecked == false ---> IsChecked = true // If IsChecked == null ---> IsChecked = false bool? isChecked; if (IsChecked == true) isChecked = IsThreeState ? (bool?)null : (bool?)false; else // false or null isChecked = IsChecked.HasValue; // HasValue returns true if IsChecked==false SetCurrentValueInternal(IsCheckedProperty, isChecked); } 

And the OnClick base runs the command:

  protected virtual void OnClick() { RoutedEventArgs newEvent = new RoutedEventArgs(ButtonBase.ClickEvent, this); RaiseEvent(newEvent); MS.Internal.Commands.CommandHelpers.ExecuteCommandSource(this); } 

Source: MSDN Reference Source

Thus, the value must be valid at the time the command is run.

+4
source

All Articles