Why could not do OneWay binding to ToggleButton IsChecked property?

女生的网名这么多〃 提交于 2019-12-12 15:52:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/4881682/why-could-not-do-oneway-binding-to-togglebutton-ischecked-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!