Reputation: 21
I am fairly new to WPF and the .NET Framework.
I have created a custom button class and have added a dependency property "Colors" which is another class that I created which defines a buttons border/face colors when enabled and disabled. In the style for this button, I am trying to use Relative Source Binding to Bind members of the "Colors" property to different Properties of the button (Border.Background, Border.BorderBrush, etc.).
Here is my button class:
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);
}
And here is the template portion of the style
<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>
This approach is unsuccessful. When I create an instance of my button class, It doesn't get drawn at all. Am I on the right path? Is there a better way to do what I want?
Upvotes: 2
Views: 293
Reputation: 28968
Your binding paths doesn't resolve. You have to use either TemplateBinding
or RelativeSoure TemplatedParent
, whenever you are inside a ControlTemplate
and want to bind to the templated control itself:
<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>
Upvotes: 1