Binding a template to background and foreground colors?

I am creating a simple control for a button. I want to draw a two-color gradient and snap two colors, so I don’t need to hardcode them in the template. But since Background and Foreground are brushes, not just colors, I'm not sure if this will work.

Can someone tell me if there is a good way to do this? it seems simple enough. Thank.

<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 colors Black and White with TemplateBindings.

+3
source share
2 answers

You can use the attached properties to add some new Color properties that you can use in 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);
    }
}

, Bindings (TemplateBindings ):

<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>
+4

. , ( ) ..

0

Source: https://habr.com/ru/post/1753373/


All Articles