更改自定义模板触发器中的绑定值

时间:2013-06-25 10:52:00

标签: wpf xaml

如何更改自定义模板中的绑定属性?

具有路径填充的按钮,该按钮绑定到按钮的前景:

<Button Style="{DynamicResource CustomButtonStyle}"Foreground="White" >
   <Path Data="PATH_DATA" Stretch="Uniform" Fill="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" ></Path>
</Button>

以下是具有覆盖模板的自定义样式:

<Style x:Key="CustomButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="{x:Null}"/>
        <Setter Property="BorderBrush" Value="White"/>
        <Setter Property="BorderThickness" Value="0"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                        <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Foreground" Value="#d5113f"/>
                        </Trigger>
                        <Trigger Property="IsPressed" Value="True">    
                            <Setter Property="Foreground" Value="#d5113f"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

但是在触发器中更改Foregroud

<Setter Property="Foreground" Value="#d5113f"/>

什么都不做

1 个答案:

答案 0 :(得分:2)

由于您将Foreground设置为固定值,根据Dependency Property Setting Precedence List,您的样式触发器不会覆盖此值。您需要将Foreground设置为Style作为另一个设置者,如下所示:

<Style x:Key="CustomButtonStyle" TargetType="{x:Type Button}">
   <Setter Property="Foreground" Value="White"/>
   ...
</Style>