Justin Pihony
Justin Pihony

Reputation: 67115

How to allow default value when using binding for custom control

All, I am working on a custom control of ours that has a Border with a Background set to the below

<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
    <GradientStop Color="#FFF7F7F7" Offset="0.164" />
    <GradientStop Color="#FFDBDBDB" Offset="0.664" />
    <GradientStop Color="#FFB3B3B3" Offset="0.978" />
</LinearGradientBrush>

However, I want to allow the user to override this. I created a dependency property of type Brush, however I cannot figure out how to bind to the Background, while still having this default in the XAML. Is this even possible?

Upvotes: 2

Views: 155

Answers (1)

Fede
Fede

Reputation: 44048

Take a look at the TemplateBinding Markup Extension

<Style TargetType="{x:Type your:YourControl}">
    <Setter Property="Background">
        <Setter.Value>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#FFF7F7F7" Offset="0.164" />
                <GradientStop Color="#FFDBDBDB" Offset="0.664" />
                <GradientStop Color="#FFB3B3B3" Offset="0.978" />
            </LinearGradientBrush>
        </Setter.Value>
    </Setter>

Then in some part of your default ControlTemplate:

<Border Background="{TemplateBinding Background}">
  ....
</Border>

This will allow the consumer to override the default Background, while maintaining the Style-defined one:

<your:YourControl/> <!-- Will use default Background -->

<your:YourControl Background="Green"/> <!-- will have Green background -->

Upvotes: 2

Related Questions