2
votes

So I have a toggle button as follows:

  <ToggleButton 
      IsChecked="{Binding IsButtonChecked, Mode=OneWay}"
      Command="{Binding DoNothing}"
      CommandParameter="{Binding ServerViewModel}"
      Content="Click Me!"></ToggleButton>

The initial value of IsButtonChecked = false

When I click the toggle button the ICommand properly fires (which is bound to a RelayCommand) and this command returns false for CanExecute. The state of the WPF ToggleButton is now Checked=true, however the backed model is still IsButtonChecked = false. Why did the UI update to a checked state, even though the bound property hasn't?

Side Note

The only way I've been able to prevent the UI from updating is creating an inverse property IsButtonNotChecked. I then bind that property to IsEnabled in the XAML. This prevents button clicks from occurring if the state is currently enabled.

2
What's the use case of this control? From what you have provided it sounds like you're starting/stopping a server. I have a few more ideas, but I don't want to provide another incorrect one.Richard Preziosi

2 Answers

0
votes

You have the binding mode set to OneWay, set it to TwoWay.

<ToggleButton Command="{Binding DoNothing}"
              CommandParameter="{Binding ServerViewModel}"
              Content="Click Me!"
              IsChecked="{Binding IsButtonChecked,
                                  Mode=TwoWay}" />
0
votes

For what its worth, here's what I did.. It looks really clunkly.

I set the binding mode to TwoWay. It didn't look like OneWay binding respected the IsChecked property.

  <ToggleButton 
      IsChecked="{Binding IsButtonChecked, Mode=TwoWay}"
      Command="{Binding DoNothing}"
      CommandParameter="{Binding ServerViewModel}"
      Content="Click Me!"></ToggleButton>

Secondly, I no-opp'ed the mutator property of IsButtonChecked.

 public bool IsButtonChecked
        {
            get
            {
                return _isButtonChecked;
            }
            set
            {
                // Prevents the IsButtonCheckedfrom incorrectly being set to a
                // enabled state, yet the model is false
                // IsButtonCheckeddoesn't seem to respect OneWay binding.               
            }
        }

Then within code behind, I update the _isButtonChecked property and call the INotifyPropertyChanged event.

internal void ShouldBeChecked(bool isChecked)
{ 
_isButtonChecked = isChecked;
 OnPropertyChanged("IsButtonChecked"); 
}

Really clunky though... Its odd that a ToggleButton doesnt respect the bound property...