【发布时间】:2015-05-21 07:46:36
【问题描述】:
<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 错误:4:找不到与引用“RelativeSource FindAncestor,AncestorType='System.Windows.Controls.ContentControl',AncestorLevel='1'' 进行绑定的源。绑定表达式:路径=前景;数据项=空;目标元素是'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>
【问题讨论】:
-
您有多个 ContentControl,这可能会导致您的 RelativeSource 绑定出现问题(即使它有效),您是否尝试过使用 ElementName 绑定?
-
如果我使用 ElementName 绑定或删除两个 ContentControl 之一,也会发生错误。
-
这很奇怪,我的意思是,它确实有效,但无论如何它都会引发错误。忽略它是很有诱惑力的,但是它抛出错误一定有一些的原因。事实是,我不知道。
-
出于好奇,如果您通过
Tag属性而不是Foreground传递颜色字符串会怎样?看起来像是颜色冲突。 -
如果我使用 ContentControl 的 Tag 属性也会出现错误。
标签: c# wpf xaml data-binding imagesource