C# 将自定义按钮背景/边框绑定到自定义属性
我对WPF和.NET框架相当陌生 我创建了一个自定义按钮类,并添加了一个依赖属性“Colors”,这是我创建的另一个类,在启用和禁用时定义按钮边框/面颜色。在这个按钮的样式中,我尝试使用相对源绑定将“Colors”属性的成员绑定到按钮的不同属性(Border.Background、Border.BorderBrush等) 这是我的按钮类:C# 将自定义按钮背景/边框绑定到自定义属性,c#,wpf,xaml,binding,C#,Wpf,Xaml,Binding,我对WPF和.NET框架相当陌生 我创建了一个自定义按钮类,并添加了一个依赖属性“Colors”,这是我创建的另一个类,在启用和禁用时定义按钮边框/面颜色。在这个按钮的样式中,我尝试使用相对源绑定将“Colors”属性的成员绑定到按钮的不同属性(Border.Background、Border.BorderBrush等) 这是我的按钮类: public class FsnButton : Button { static FsnButton() { DefaultS
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>
这种方法是不成功的。当我创建button类的实例时,它根本不会被绘制。我走对了吗?是否有更好的方法来执行我想要的操作?您的绑定路径无法解析。当您在
控件模板
中并且想要绑定到模板控件本身时,您必须使用模板绑定
或相对性TemplatedParent
:
<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>