我尝试为我的标签创建一个 ControlTemplate,如下所示:
<Style TargetType="{x:Type Label}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Label}">
<Grid x:Name="LayoutRoot" Background="White">
<Rectangle Height="30" HorizontalAlignment="Left" Margin="10"
Stroke="transparent"
VerticalAlignment="Top" Width="3"
Fill="#FF259FED" />
<ContentPresenter HorizontalAlignment="Left" Margin="17,0,0,0" RecognizesAccessKey="True"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="#7A7E81" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
我想在创建控件时填充矩形的颜色,例如:
<Label Content="Prénom" VerticalAlignment="Top" CouleurRectangle="#FF259FED" />
那么,当我创建控件时,如何更改我的 controlTemplate 中的属性“填充”以动态设置矩形的颜色?
多谢。
编辑:这是解决方案,我创建了一个从 Label 继承的新类,如下所示:
Public Class LblTitreChamp
Inherits Label
Public Shared ReadOnly CouleurProperty As DependencyProperty =
DependencyProperty.Register("CouleurRectangle", GetType(SolidColorBrush), GetType(LblTitreChamp))
''' <summary>Propriété pour insérer une couleur au début du Label</summary>
Public Property CouleurRectangle As SolidColorBrush
Get
Return GetValue(CouleurProperty)
End Get
Set(ByVal value As SolidColorBrush)
SetValue(CouleurProperty, value)
End Set
End Property
End Class
然后,在我的 CControlTemplate 中:
<Style TargetType="{x:Type local:LblTitreChamp}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:LblTitreChamp}">
<Grid x:Name="LayoutRoot" Background="White">
<Rectangle Height="30" HorizontalAlignment="Left" Margin="10"
Stroke="transparent"
VerticalAlignment="Top" Width="3"
Fill="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Label}}, Path=CouleurRectangle}"/>
<ContentPresenter HorizontalAlignment="Left" Margin="17,0,0,0" RecognizesAccessKey="True"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="#7A7E81" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
最后,创建一个新标签:
<my:LblTitreChamp Content="ID" VerticalAlignment="Top" CouleurRectangle="Black" />
非常感谢你:)