简体   繁体   中英

Why could not do OneWay binding to ToggleButton IsChecked property?

ToggleButton support ICommand, so I create many command such TogglePlayPause, ToggleMute and it work fine but i need to bind IsChecked property too so its checked state always show correct state. but when I create OneWay binding mode for ToggleButton and when I Press ToggleButton, the binding will lost.

The question is why ToggleButton support ICommand but does not support OneWay binding? I can set TwoWay binding, but it is bad idea when ToggleButton use Command, because the actual operation handled by Command and it should not be duplicated with TwoWay binding, also some times it is not possible. in my case Command=TogglePlayPause IsChecked={Bind to IsMediaPlaying} IsMediaPlaying should be readonly.

So please tell me how use ToggleButton with Command and bind its IsChecked property?

You can write your own OneWayToggleButton by deriving from ToggleButton and override what happens when the button is clicked:

public class OneWayToggleButton : ToggleButton
{
    protected override void OnClick()
    {
        RaiseEvent(new RoutedEventArgs(ClickEvent, this));
        if (Command != null && Command.CanExecute(CommandParameter))
            Command.Execute(CommandParameter);
    }
}

and then IsChecked won't be modified by the button itself and can only be changed via the binding. But because we are still using the IsChecked property of the ToggleButton , the control will look and behave normally.

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