Pea*_*son 5 c# data-binding wpf xaml imagesource
<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>
Run Code Online (Sandbox Code Playgroud)
此示例显示了两个图标。图标具有父 ContentControl 的颜色。它工作正常。
但输出显示绑定错误:
System.Windows.Data 错误:4:无法找到引用“RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ContentControl', AncestorLevel='1''的绑定源。BindingExpression:Path=前景;数据项=空;目标元素是“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>
Run Code Online (Sandbox Code Playgroud)
只需设置一个名称,错误就会消失:
<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>
Run Code Online (Sandbox Code Playgroud)
绑定到 Parent 的更奇特的方式:
RelativeSource={RelativeSource TemplatedParent}
Run Code Online (Sandbox Code Playgroud)
编辑:
如果您想抑制此 VS 错误,请访问链接