2011-02-03 75 views
3

ToggleButton支持ICommand,所以我創建了很多命令,例如TogglePlayPause,ToggleMute,它工作正常,但我需要綁定IsChecked屬性,所以它的checked狀態總是顯示正確的狀態。但是當我爲ToggleButton創建OneWay綁定模式並且當我按下ToggleButton時,綁定將會丟失。爲什麼不能將OneWay綁定到ToggleButton的IsChecked屬性?

問題是爲什麼ToggleButton支持ICommand但不支持OneWay綁定? 我可以設置TwoWay綁定,但是當ToggleButton使用Command時,這是個壞主意,因爲Command處理的實際操作不應該與TwoWay綁定一起復制,有時候這也是不可能的。在我的情況下 Command = TogglePlayPause IsChecked = {綁定到IsMediaPlaying} IsMediaPlaying應該是隻讀的。

那麼請告訴我如何在命令中使用ToggleButton並綁定其IsChecked屬性?

回答

3

您可以通過從ToggleButton派生寫自己OneWayToggleButton並覆蓋單擊該按鈕時會發生什麼:

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

然後IsChecked不會通過按鈕本身進行修改,只能通過改變捆綁。但是因爲我們仍在使用ToggleButtonIsChecked屬性,所以控件的外觀和行爲都會正常。

+0

我不能使用這個,因爲其他人創建的接口,我只是有它的DLL。我使用代碼進行動態綁定,因此我無法使用自己的覆蓋類。 – Madnik7G 2011-02-03 06:46:45

相關問題