以下代码将a绑定GradientStop到Background.Color属性TemplatedParent.一切正常但我在输出窗口中收到绑定错误:
System.Windows.Data错误:2:找不到目标元素的管理FrameworkElement或FrameworkContentElement.BindingExpression:路径= Background.Color; 的DataItem = NULL; target元素是'GradientStop'(HashCode = 6944299); 目标属性是'颜色'(类型'颜色')
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfBindingTest.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="100" Height="100">
<Window.Resources>
<ControlTemplate x:Key="GradientTemplate" TargetType="{x:Type ContentControl}">
<Border BorderThickness="1" BorderBrush="{TemplateBinding Background}">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="{Binding Path=Background.Color,
RelativeSource={RelativeSource TemplatedParent}}" Offset="1"/>
<GradientStop Color="White" Offset="0"/>
</LinearGradientBrush>
</Border.Background>
<ContentPresenter/>
</Border>
</ControlTemplate>
</Window.Resources>
<Grid x:Name="LayoutRoot">
<ContentControl Background="Green" Template="{StaticResource GradientTemplate}" >
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" Text="X" />
</ContentControl>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)