Template Binding to background and foreground colors?
I'm building a simple ControlTemplate for a Button. I want to draw a 2 color gradient, and bind the two colors so I don't need to hard code t开发者_开发技巧hem in the template. But since Background and Foreground are Brushes and not just Colors, I'm not sure this will work.
Can anyone tell me if there is a good way to do this? it seems simple enough. Thanks.
<ControlTemplate x:Key="ElipseButton" TargetType="Button">
<Ellipse>
<Ellipse.Fill>
<RadialGradientBrush RadiusX="1" RadiusY="1" GradientOrigin="0.7,0.8">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="Black" Offset="1"/>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
</ControlTemplate>
I want to replace the 'Black' and 'White' colors with TemplateBindings.
You can use attached properties to add some new Color properties that you can use on Button:
public class ColorExtensions
{
public static readonly DependencyProperty ColorFrontProperty = DependencyProperty.RegisterAttached(
"ColorFront",
typeof(Color),
typeof(ColorExtensions),
new UIPropertyMetadata(Colors.White));
public static Color GetColorFront(DependencyObject target)
{
return (Color)target.GetValue(ColorFrontProperty);
}
public static void SetColorFront(DependencyObject target, Color value)
{
target.SetValue(ColorFrontProperty, value);
}
public static readonly DependencyProperty ColorBackProperty = DependencyProperty.RegisterAttached(
"ColorBack",
typeof(Color),
typeof(ColorExtensions),
new UIPropertyMetadata(Colors.Black));
public static Color GetColorBack(DependencyObject target)
{
return (Color)target.GetValue(ColorBackProperty);
}
public static void SetColorBack(DependencyObject target, Color value)
{
target.SetValue(ColorBackProperty, value);
}
}
You can then set these on any instance and access them in your template using normal Bindings (TemplateBindings won't work here):
<Button Content="Click Me" local:ColorExtensions.ColorFront="Red">
<Button.Template>
<ControlTemplate TargetType="Button">
<Ellipse>
<Ellipse.Fill>
<RadialGradientBrush RadiusX="1" RadiusY="1" GradientOrigin="0.7,0.8">
<GradientStop Color="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(local:ColorExtensions.ColorFront)}" Offset="0"/>
<GradientStop Color="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(local:ColorExtensions.ColorBack)}" Offset="1"/>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
</ControlTemplate>
</Button.Template>
</Button>
Personally, I would just put the entire Brush into your template. This gives you much more control, later, as it allows you to change (via template changes) the brush from a radial gradient to a linear gradient, etc.
精彩评论