<Window x:Class="Project.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="100" Height="400">
<Window.Resources>
<Style x:Key="IconStyle" TargetType="{x:Type Image}">
<Setter Property="Source">
<Setter.Value>
<DrawingImage>
<DrawingImage.Drawing>
<GeometryDrawing Brush="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentControl}}, Path=Foreground}">
<GeometryDrawing.Geometry>
<PathGeometry Figures="M 0,0 0,10 10,5" />
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingImage.Drawing>
</DrawingImage>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel>
<ContentControl Foreground="Red">
<Image Style="{StaticResource IconStyle}" />
</ContentControl>
<ContentControl Foreground="Blue">
<Image Style="{StaticResource IconStyle}" />
</ContentControl>
</StackPanel>
</Window>
这个例子展示了两个图标。这些图标具有父级ContentControl的颜色。它能正常工作。
但是输出显示绑定错误:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ContentControl', AncestorLevel='1''. BindingExpression:Path=Foreground; DataItem=null; target element is 'GeometryDrawing' (HashCode=8154127); target property is 'Brush' (type 'Brush')
为什么会出现这个错误?我该如何修复它或者可以忽略它吗?
编辑
这种情况下也会出现错误:
<Window x:Class="Project.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="100" Height="400">
<Window.Resources>
<Style x:Key="IconStyle" TargetType="{x:Type ContentControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<Image>
<Image.Source>
<DrawingImage>
<DrawingImage.Drawing>
<GeometryDrawing Brush="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentControl}}, Path=Foreground}">
<GeometryDrawing.Geometry>
<PathGeometry Figures="M 0,0 0,10 10,5" />
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel>
<ContentControl Foreground="Red" Style="{StaticResource IconStyle}" />
<ContentControl Foreground="Blue" Style="{StaticResource IconStyle}" />
</StackPanel>
</Window>