使用绑定进行自定义控件时如何允许默认值

时间:2013-04-15 20:18:59

标签: c# wpf xaml .net-4.0 styles

全部,我正在制作我们的自定义控件,其Border设置为Background

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

但是,我想允许用户覆盖它。我创建了类型为Brush的依赖项属性,但是我无法弄清楚如何绑定到Background,同时在XAML中仍然具有此默认值。这甚至可能吗?

1 个答案:

答案 0 :(得分:2)

查看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>

然后在默认ControlTemplate的某些部分:

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

这将允许消费者覆盖默认背景,同时保持样式定义的背景:

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

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