c# - 将自定义按钮背景/边框绑定到自定义属性
问题描述
我对 WPF 和 .NET 框架相当陌生。
我创建了一个自定义按钮类并添加了一个依赖属性“Colors”,这是我创建的另一个类,它定义了启用和禁用时的按钮边框/面颜色。在此按钮的样式中,我尝试使用相对源绑定将“颜色”属性的成员绑定到按钮的不同属性(Border.Background、Border.BorderBrush 等)。
这是我的按钮类:
public class FsnButton : Button
{
static FsnButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(FsnButton), new FrameworkPropertyMetadata(typeof(FsnButton)));
}
public FsnButton()
{
Colors = FsnColors.GrayBtnColors;
}
public GuiTypes.ButtonColors Colors
{
get { return GetValue(ColorsProperty) as GuiTypes.ButtonColors; }
set { SetValue(ColorsProperty, value); }
}
public static readonly DependencyProperty ColorsProperty =
DependencyProperty.Register("Colors", typeof(GuiTypes.ButtonColors), typeof(FsnButton), null);
}
这是样式的模板部分
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:FsnButton">
<Border Name="Face" CornerRadius="3"
Background="{ Binding RelativeSource={RelativeSource Self}, Path=Colors.Enabled.Face}"
BorderThickness="1"
BorderBrush="{ Binding RelativeSource={RelativeSource Self}, Path=Colors.Enabled.Border}">
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="{ Binding RelativeSource={RelativeSource Self}, Path=Colors.Enabled.Border}"></Setter>
<Setter Property="Button.Effect">
<Setter.Value>
<DropShadowEffect Color="DarkSlateGray" Direction="320" ShadowDepth="0" BlurRadius="5" Opacity="0.5"></DropShadowEffect>
</Setter.Value>
</Setter>
<Setter Property="RenderTransform">
<Setter.Value>
<TranslateTransform X="3" Y="3" />
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
这种方法是不成功的。当我创建按钮类的实例时,它根本不会被绘制。我在正确的道路上吗?有没有更好的方法来做我想做的事?
解决方案
您的绑定路径无法解析。每当您在 a 中并想要绑定到模板化控件本身时,您都必须使用TemplateBinding
or :RelativeSoure TemplatedParent
ControlTemplate
<ControlTemplate TargetType="local:FsnButton">
<!-- TemplatedParent binding source -->
<Border Name="Face"
Background="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Colors.Enabled.Face}"
BorderBrush="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Colors.Enabled.Border}" />
<!-- TemplateBinding -->
<Border Name="Face"
Background="{TemplateBinding Colors.Enabled.Face}"
BorderBrush="{TemplateBinding Colors.Enabled.Border}" />
</ControlTemplate>
推荐阅读
- linux - 制作 PIE 对象时不能使用 .data'
- android - Android APP Bundles apk 无法通过 bundletool 安装(INSTALL_PARSE_FAILED_NO_CERTIFICATES)
- arrays - 将多列堆叠为一列而不忽略空白单元格
- swift - 未触发 Combine 中的 CombineLatest
- ruby-on-rails - 仅遍历持久对象
- css - SVG 转换滞后于 firefox
- git - 为什么我已经添加了 git remote add 后需要在本地分支上设置上游?
- anaconda - Conda 环境损坏
- mule - Mule 4 /DW 2.0 如何根据“标题”插入此 JSON?
- java - 在 pod 意外关闭时运行退出逻辑的最佳方法