我无法弄清楚,为什么这不起作用:
我有两个按钮:
<Button Content="qwerty" BorderBrush="Tomato">
<Button Content="dvorak">
我用这种风格调整了这些按钮的外观:
<Style TargetType="Button">
<Setter Property="BorderBrush" Value="DarkRed" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="RootElement" CornerRadius="4">
<Border.Background>
<SolidColorBrush x:Name="BorderBrush" Color="{TemplateBinding BorderBrush}" />
</Border.Background>
...
第一个按钮的颜色应该在 x:Name="BorderBrush"
中设置为“番茄”,因为我在按钮定义中指定了它。
第二个按钮没有BorderBrush="..."
指定,因此默认颜色 DarkRed
来自 <Setter Property="BorderBrush" Value="DarkRed" />
应该使用。
但它根本不使用任何颜色。
如果我像这样硬编码颜色 <SolidColorBrush x:Name="BorderBrush" Color="DarkRed" />
,然后它就可以工作了,但这并不好,因为我需要能够在按钮定义中设置颜色。
最佳答案
BorderBrush
属性持有一个 Brush
对象,但您尝试将其绑定(bind)到 SolidColorBrush< 的
无法工作。Color
属性
您需要在边框的 Background
属性上使用 TemplateBinding
:
<Border x:Name="RootElement" CornerRadius="4"
Background="{TemplateBinding BorderBrush}">
作为替代解决方案,您可以借助 RelativeSource TemplatedParent
绑定(bind)父级 BorderBrush
的 Color
属性:
<Border.Background>
<SolidColorBrush x:Name="BorderBrush"
Color="{Binding RelativeSource={RelativeSource TemplatedParent},
Path=BorderBrush.Color}" />
</Border.Background>
关于c# - 使用自定义属性值在模板中设置颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25472440/