使用样式时,ToggleButton的命令不会触发

时间:2014-05-01 10:46:42

标签: wpf styles command

以下ToggleButton按预期工作:

<ToggleButton Command="{Binding ToggleCommand}"
              RenderOptions.BitmapScalingMode="HighQuality"
              ToolTip=".." 
              VerticalAlignment="Stretch"
              Focusable="False" IsChecked="False" Margin="2" Padding="0"
              Style="{StaticResource {x:Static ToolBar.ToggleButtonStyleKey}}">
     <Image Source="/..;component/Resources/...png" Height="26"/>
</ToggleButton>

点击后会执行ToggleCommand的实施。

然后我决定使用这样的风格:

<Style x:Key="ButtonToggle" TargetType="ToggleButton">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <ToggleButton RenderOptions.BitmapScalingMode="HighQuality"
                              VerticalAlignment="Stretch"
                              Focusable="False" IsChecked="False" Margin="2" Padding="0"
                              Style="{StaticResource {x:Static ToolBar.ToggleButtonStyleKey}}">
                    <Image Source="/..;component/Resources/...png" Height="26"/>
                </ToggleButton>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

与:

一起
<ToggleButton DockPanel.Dock="Right" Command="{Binding ToggleCommand}" ToolTip=".."
              Style="{StaticResource ButtonToggle}" />

显示正常。
与ToggleCommand绑定是可以的 就在我点击按钮时,ToggleCommand的执行没有被执行 任何人都可以解释为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

您需要在controlTemplate中绑定控件的命令
在样式中的togglebutton中添加Command =“{TemplateBinding Command}”:

            <Style x:Key="ButtonToggle" TargetType="ToggleButton">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                        <ToggleButton RenderOptions.BitmapScalingMode="HighQuality"
                          Command="{TemplateBinding Command}"
                          VerticalAlignment="Stretch"
                          Focusable="False" IsChecked="False" Margin="2" Padding="0"
                          Style="{StaticResource {x:Static ToolBar.ToggleButtonStyleKey}}">
                            <Image Source="/..;component/Resources/...png" Height="26"/>
                        </ToggleButton>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>