c# - 使用自定义属性值在模板中设置颜色

标签 c# wpf xaml

我无法弄清楚,为什么这不起作用:

我有两个按钮:

<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)父级 BorderBrushColor 属性:

<Border.Background>
    <SolidColorBrush x:Name="BorderBrush" 
      Color="{Binding RelativeSource={RelativeSource TemplatedParent}, 
                      Path=BorderBrush.Color}" />
</Border.Background>

关于c# - 使用自定义属性值在模板中设置颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25472440/

相关文章:

c# - 如何在 XAML 中指定 DataGrid 的 ItemsSource 类型?

c# - Asp.NET 定时器控件不工作

c# - 在 C# 中,有没有办法将同一类中的代码分离到不同的文件中?

c# - 焦点更改时文本框格式丢失

wpf - 搜索默认的 "check mark"图标

c# - 通用项目的 WPF 转换

c# - 图像已保存,但不会加载

c# - 使用 Exchange EWS... 不知道如何访问 dll?

c# - 在 WPF 中创建可重用的界面元素

wpf - 如何使用 MVVM 和 MVVM 工具包将属性绑定(bind)到文本框?