IsPressed触发器不起作用

时间:2014-09-17 08:24:03

标签: wpf xaml button triggers

样式位于参考资料中:

<Style x:Key="RoundCornerSmart" TargetType="{x:Type vk:SmartButton}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type vk:SmartButton}">
                            <Border CornerRadius="8" BorderBrush="#006AB6" BorderThickness="1" Name="border" Background="{TemplateBinding Background}">
                                <Grid x:Name="grid" >
                                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
                                </Grid>
                            </Border>
                            <ControlTemplate.Triggers>

                                <Trigger Property="IsPressed" Value="True">
                                    <Setter Property="Background" TargetName="border">
                                        <Setter.Value>
                                            LightGray
                                        </Setter.Value>
                                    </Setter>
                                </Trigger>

                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>

                <Setter Property="Command" Value="{Binding KeyCommand}" />
                <Setter Property="FontSize" Value="8"/>
                <Setter Property="Height" Value="52"/>
                <Setter Property="Width" Value="52"/>
                <Setter Property="Margin" Value="10"></Setter>
                <Setter Property="Foreground" Value="Black"></Setter>
                <Setter Property="Background" Value="White"></Setter>
                <Setter Property="BorderBrush" Value="Black"></Setter>
            </Style>

我有一个名为SmartButton的类,它扩展了Button类。

<vk:SmartButton Content="Some content" Grid.Column="3" Style="{DynamicResource RoundCornerSmart}" />

对于这个按钮,按下它时背景保持不变(白色),我需要它是LightGrey。我做错了什么?

2 个答案:

答案 0 :(得分:0)

样式RoundCorner设置为Type {x:Type Button}。现在,如果你想将它应用到另一个对象,比如vk:SmartButton你需要创建新的样式,适合该类型。

TargetType={x:Type vk:SmartButton}

答案 1 :(得分:0)

你应该收到XamlParseException,其中包含以下内容:

  

&#39;设置属性&#39; System.Windows.FrameworkElement.Style&#39;抛出异常。&#39;行号&#39; 154&#39;和行位置&#39; 44&#39;。

如果您查看了Exception的详细信息并查看了内部Exception,您会看到类似的内容:

  

&#39; Button&#39; TargetType与元素的类型不匹配&#39; SmartButton&#39;。

原因很清楚......当您打算提供新的{{1}时,您不能将Style一种类型的ControlTemplate应用于另一种类型的实例,尤其是 } 为了它。要在自定义Style上使用Button,您需要复制它并将Style.TargetType属性设置为:

<Style x:Key="SmartRoundCorner" TargetType="{x:Type YourPrefix:SmartButton}">
    ...
</Style>

值得指出的是,您可能根本不需要扩展Button类,因为WPF提供了许多其他方法来自定义标准Button

相关问题