WPF:使用控件触发器中的依赖项属性中的值更新前台



我在 WPF 中的自定义控件有以下样式:

<Style TargetType="{x:Type local:BooleanIndicator}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:BooleanIndicator}">
<Border Name="border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding Foreground}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="2">
<StackPanel Orientation="Horizontal"
Margin="3">
<Label Name="symbol"
FontFamily="Segoe MDL2 Assets"
FontSize="{TemplateBinding FontSize}"
Foreground="{TemplateBinding Foreground}"
VerticalAlignment="Center"
Content="{TemplateBinding Symbol}"/>
<ContentPresenter Margin="3,0,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
RecognizesAccessKey="True"/>
</StackPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsActive"
Value="True">
<Setter Property="Foreground"
Value="{Binding ActiveForeground, RelativeSource={RelativeSource TemplatedParent}}" />
</Trigger>
<Trigger Property="IsActive"
Value="False">
<Setter Property="Foreground"
Value="Gray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

使用依赖属性"ActiveForeground":

public Brush ActiveForeground
{
get { return (Brush)GetValue(ActiveForegroundProperty); }
set { SetValue(ActiveForegroundProperty, value); }
}
public static readonly DependencyProperty ActiveForegroundProperty =
DependencyProperty.Register("ActiveForeground",
typeof(Brush),
typeof(BooleanIndicator),
new UIPropertyMetadata(Brushes.DarkGreen));

但是它不起作用 - 前景色不会更新。如果我直接更改触发器中的颜色,例如<Setter Property="Foreground" Value="DarkGreen" />有效...这是怎么回事?

您必须在ControlTemplate中设置SetterTargetName

<Setter Property="Foreground" TargetName="symbol" Value="{Binding ActiveForeground, RelativeSource={RelativeSource TemplatedParent}}" />

如果要设置控件本身的Foreground属性,则应使用Style触发器:

<Style TargetType="{x:Type local:BooleanIndicator}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:BooleanIndicator}">
<Border Name="border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding Foreground}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="2">
<StackPanel Orientation="Horizontal"
Margin="3">
<Label Name="symbol"
FontFamily="Segoe MDL2 Assets"
FontSize="{TemplateBinding FontSize}"
Foreground="{TemplateBinding Foreground}"
VerticalAlignment="Center"
Content="{TemplateBinding Symbol}"/>
<ContentPresenter Margin="3,0,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
RecognizesAccessKey="True"/>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Gray" />
<Style.Triggers>
<Trigger Property="IsActive" Value="True">
<Setter Property="Foreground"
Value="{Binding ActiveForeground, RelativeSource={RelativeSource Self}}" />
</Trigger>
</Style.Triggers>
</Style>

最新更新