简体   繁体   English

为什么不能将OneWay绑定到ToggleButton IsChecked属性?

[英]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. ToggleButton支持ICommand,所以我创建了许多命令,如TogglePlayPause,ToggleMute,它工作正常但我需要绑定IsChecked属性,所以它的检查状态总是显示正确的状态。 but when I create OneWay binding mode for ToggleButton and when I Press ToggleButton, the binding will lost. 但是当我为ToggleButton创建OneWay绑定模式时,当我按下ToggleButton时,绑定将丢失。

The question is why ToggleButton support ICommand but does not support OneWay binding? 问题是为什么ToggleButton支持ICommand但不支持OneWay绑定? 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. 我可以设置TwoWay绑定,但是当ToggleButton使用Command时,这是个坏主意,因为Command处理的实际操作不应该与TwoWay绑定重复,有时也是不可能的。 in my case Command=TogglePlayPause IsChecked={Bind to IsMediaPlaying} IsMediaPlaying should be readonly. 在我的情况下Command = TogglePlayPause IsChecked = {Bind to IsMediaPlaying} IsMediaPlaying应该是readonly。

So please tell me how use ToggleButton with Command and bind its IsChecked property? 那么请告诉我如何使用ToggleButton与Command并绑定其IsChecked属性?

You can write your own OneWayToggleButton by deriving from ToggleButton and override what happens when the button is clicked: 您可以通过从ToggleButton派生来编写自己的OneWayToggleButton ,并覆盖单击按钮时发生的情况:

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. 然后IsChecked将不会被按钮本身修改,只能通过绑定进行更改。 But because we are still using the IsChecked property of the ToggleButton , the control will look and behave normally. 但是因为我们仍在使用ToggleButtonIsChecked属性,所以控件的外观和行为都会正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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