<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 的颜色。它工作正常。
但输出显示绑定(bind)错误:
System.Windows.Data 错误:4:找不到与引用“RelativeSource FindAncestor,AncestorType='System.Windows.Controls.ContentControl',AncestorLevel='1'' 绑定(bind)的源。绑定(bind)表达式:路径=前景;数据项=空;目标元素是 'GeometryDrawing' (HashCode=8154127);目标属性是“画笔”(类型“画笔”)
为什么会出现这个错误?我该如何修复它或忽略它?
编辑
在这种情况下也会出现错误:
<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>
最佳答案
只需设置一个名称,错误就会消失:
<GeometryDrawing x:Name="GeometryDrawing" Brush="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Foreground}">
<GeometryDrawing.Geometry>
<PathGeometry Figures="M 0,0 0,10 10,5" />
</GeometryDrawing.Geometry>
</GeometryDrawing>
绑定(bind)到父级的更奇特的方式:
RelativeSource={RelativeSource TemplatedParent}
编辑:
如果您想抑制此 VS 错误,请访问 link
关于c# - DrawingImage 样式绑定(bind)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29123527/