【发布时间】:2020-08-11 12:24:54
【问题描述】:
这似乎应该很简单,但我想不通。
我正在尝试更改元素上“填充”属性的工作样式设置器,以在 Setter.Value 中的 XAML 中实际声明 SolidColorBrush 对象。不幸的是,在我的画笔声明中,我似乎无法“获取”我试图设置其 Fill 的对象的 DataContext。我该怎么做?
下面是带有 setter 的样式。它使用一个转换器,该转换器接受一个枚举值(“Usage”)并返回一个颜色值。转换器很好,但绑定失败,因为它找不到对象。
<core:UsageToColorConverter x:Key="CvtUsageToColor"/>
<Style x:Key="RegionBandStyle"
TargetType="{x:Type tk:CartesianPlotBandAnnotation}">
<!-- Help Intellisense show us the correct bindings when coding -->
<d:Style.DataContext>
<x:Type Type="gci:IProfileRegion" />
</d:Style.DataContext>
<Setter Property="Fill">
<Setter.Value>
<SolidColorBrush >
<SolidColorBrush.Color>
<!-- THIS BINDING FAILS: It cannot find the "ancestor" CartesianPlotBandAnnotation
in order to get at its DataContext
-->
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type tk:CartesianPlotBandAnnotation}}"
Path="DataContext.(gci:IProfileRegion.Usage)"
Converter="{StaticResource CvtUsageToColor}"/>
</SolidColorBrush.Color>
</SolidColorBrush>
</Setter.Value>
</Setter>
</Style>
绑定失败并显示此消息:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='Telerik.Windows.Controls.ChartView.CartesianPlotBandAnnotation', AncestorLevel='1''. BindingExpression:Path=DataContext.Usage; DataItem=null; target element is 'SolidColorBrush' (HashCode=39731869); target property is 'Color' (type 'Color')
我想这是有道理的。我模糊的理解是画笔不在视觉(或逻辑)树中,对吧?所以它找不到祖先?是这个原因吗?
这个 Setter 的原始版本可以工作,但要简单得多。它只是使用了一个类似的转换器,它返回 SolidColorBrush 而不是颜色:
<Setter Property="Fill" Value="{Binding Usage, Converter={StaticResource CvtUsageToBrush}}"/>
这很好,但不幸的是(出于不相关的原因),我需要以另一种方式做事;我需要自己使用属性元素语法明确声明画笔
谁能告诉我我需要什么绑定巫术才能在我的SolidColorBrush 颜色绑定中获取CartesianPlotBandAnnotation 的DataContext?
(无论我在逻辑树和视觉树上阅读多少次,这种绑定问题都会让我头晕目眩。我的搜索不断提出相关主题,但不是我想要的。)
【问题讨论】:
-
我可以请您访问my question吗?猜你知道答案。
-
我三思而后行,只有
RelativeSource="{RelativeSource Self}" -
不幸的是,这似乎不起作用。我尝试过这个。我没想到会这样,因为它只是让我回到我正在声明的同一个 SolidColorBrush。 SolidColorBrush 没有 DataContext,因为它不是 FrameworkElement
标签: wpf data-binding visual-tree