绑定切换按钮,两个命令

问题描述:

我有一个切换按钮在我的Silverlight应用程序如下:绑定切换按钮,两个命令

<ToggleButton Content="ToggleButton" Margin="0,30,0,0" Style="{StaticResource ChkToggleButton}" /> 

肘目前正在改变切换而已视觉状态。
但是,我需要将每个切换与不同的命令绑定。对于例如:开启按钮按下1,运行command1然后再次按下按钮,运行command2

这怎么办?

使用Triggers用于这种目的:

<ToggleButton Content="ToggleButton" Margin="0,30,0,0" Style="{StaticResource ChkToggleButton}"> 
    <i:Interaction.Triggers> 
     <i:EventTrigger EventName="Checked"> 
      <i:InvokeCommandAction Command="{Binding FirstCommand}" 
            CommandParameter="{Binding SomeParameter}" /> 
     </i:EventTrigger> 
     <i:EventTrigger EventName="Unchecked"> 
      <i:InvokeCommandAction Command="{Binding SecondCommand}" 
            CommandParameter="{Binding AnotherParameter}" /> 
     </i:EventTrigger> 
    </i:Interaction.Triggers> 
</ToggleButton> 

如果你没有Interactivity您可以通过安装Expression Blend SDK或作为NuGet package得到它。

+1

我没有立即知道我映射到的xmlns,所以我查了一下那些可能不知道的。它是System.Windows.Interactivity并位于Blend SDK中。你可以在这里得到它:http://www.nuget.org/packages/System.Windows.Interactivity.WPF/ – 2014-11-24 22:18:50

+0

@MattBecker,谢谢。更新了答案。 – 2014-11-25 19:04:55

+0

@Pang谢谢,更新了答案。 – 2018-02-14 14:44:21

使用单个命令并记录切换状态。

有一个视图模型(最好还是一些代码隐藏),并让它使用这两个输入来决定实际需要完成的事情。