WPF将ControlTemplate的内容绑定到控件中的属性?

mar*_*mnl 4 wpf wpf-controls .net-3.5

我想将Button ControlTemplate中的Border.Background绑定到我的按钮的Background属性.通常我会使用TemplateBinding:

  <Style TargetType="Button" x:Key="ColuredButton">
                <Setter Property="Background" Value="LightGreen"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Border x:Name="Border" CornerRadius="2" BorderThickness="1" BorderBrush="Gray">
                               <Border.Background>
                                    <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                                        <GradientStop Color="{TemplateBinding Foreground}"/>
                                        <GradientStop Color="{TemplateBinding Background}"/>
                                    </LinearGradientBrush>
                                </Border.Background>
                                    <ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True" />
                            </Border> 
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
Run Code Online (Sandbox Code Playgroud)

但我收到错误:"如果不在模板中,则无法设置TemplateBinding"..但我在模板中!(如果我不使用LinearGradientBrush并将边框Backround属性直接绑定到{TemplateBinding Background},它可以工作....

WPF*_*-it 8

作为@Snowbear说,你应该绑定ColorColor而不是ColorBrush.但是在他的解决方案中,TemplateBinding使用Path诸如Foreground.Colorisnt之类的深层属性作为绑定标记的一部分.

所以使用以下......

    <Border.Background>
      <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
         <GradientStop Color="{Binding Foreground.Color,
                               RelativeSource={RelativeSource TemplatedParent}}"
                       Offset="0.2"/>
         <GradientStop Color="{Binding Background.Color,
                               RelativeSource={RelativeSource TemplatedParent}}"
                       Offset="0.6"/>
      </LinearGradientBrush>
   </Border.Background>
Run Code Online (Sandbox Code Playgroud)

它应该工作.