我有一个设置了控制模板(包括一些控制模板触发器)的按钮,我想在DataTrigger上更改其文本颜色。我已经读到我无法访问模板的TargetName(“ theContent”),因为它具有自己的范围,那么如何实现呢?
<Button BorderThickness="0" MaxWidth="94" Height="26" Margin="1,0,0,0">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="theBorder" CornerRadius="15" BorderThickness="0" Background="{TemplateBinding Background}">
<Label x:Name="theContent" VerticalContentAlignment="Center" Foreground="White" FontWeight="Bold">
<TextBlock Text="..." TextTrimming="CharacterEllipsis"></TextBlock>
</Label>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="False">
<Setter Property="Background" Value="#1A65AF"></Setter>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#4d87c0"></Setter>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="#004b95"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{...}" Value="..."></Condition>
<Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsEnabled}" Value="False"></Condition>
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="#ad4811"/>
<Setter Property="Foreground" Value="#7F7F7F" /> // does nothing
<Setter TargetName="theContent" Property="Foreground" Value="#7F7F7F" /> // target not found
</MultiDataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
<!--<Button.Content>
<Label x:Name="theContent" VerticalContentAlignment="Center" Foreground="White" FontWeight="Bold">
<TextBlock Text="..." TextTrimming="CharacterEllipsis"></TextBlock>
</Label>
</Button.Content>-->
</Button>
我尝试但不起作用的2个setter是:
<Setter Property="Foreground" Value="#7F7F7F" /> // does nothing
<Setter TargetName="theContent" Property="Foreground" Value="#7F7F7F" /> // target not found
答案 0 :(得分:0)
在控制模板中,您只需要使用TemplateBinding
而不是将值硬编码为White
。
<Border x:Name="theBorder" CornerRadius="15" BorderThickness="0" Background="{TemplateBinding Background}">
<Label x:Name="theContent" VerticalContentAlignment="Center" Foreground="{TemplateBinding Foreground}" FontWeight="Bold">
<TextBlock Text="..." TextTrimming="CharacterEllipsis"></TextBlock>
</Label>
</Border>
这样做将取决于按钮的Foreground
属性。通常,如果需要动态更改ControlTemplate
中的任何属性,则需要使用TemplateBinding
(例如FontWeight
属性)。现在,您的StyleTrigger
设置器将按预期工作。
顺便说一句,Foreground="{TemplateBinding Foreground}"
只是
Foreground="{Binding Foreground, RelativeSource={RelativeSource TemplatedParent}}"