这看起来应该像馅饼一样简单,但我无法理解。
我正在尝试更改元素上"Fill"属性的工作样式设置器,以便在Setter.Value
的XAML中实际声明SolidColorBrush
对象。不幸的是,在我的brush声明中,我似乎无法"获取"我试图设置其Fill的对象的DataContext。我该怎么做?
下面是带有setter的样式。它使用一个转换器,该转换器接受一个枚举值("Usage"(并返回一个Color值。转换器很好,但绑定失败,因为它找不到对象。
<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')
我想这是有道理的。我的理解是Brush不在视觉(或逻辑(树中,对吧?所以它找不到祖先?这是原因吗?
这个Setter的原始版本有效,但它要简单得多。它只是使用了一个类似的转换器,返回SolidColorBrush
而不是颜色:
<Setter Property="Fill" Value="{Binding Usage, Converter={StaticResource CvtUsageToBrush}}"/>
这很好,但不幸的是(由于无关的原因(,我需要用另一种方式做事;我需要使用属性元素语法明确声明Brush
有人能告诉我在SolidColorBrush
颜色绑定中,我需要在CartesianPlotBandAnnotation
的DataContext中获得什么绑定voodoo吗?
(这是一种绑定问题,无论我在逻辑树和视觉树上读了多少遍,它都会让我头疼。我的搜索一直会提到相关的主题,但不是我想要的。(
更新:在接口绑定的情况下,将Path设置为"(gci:IProfileRegion.Usage("就足够了。我刚刚测试了这段代码,并确认它工作正常:https://github.com/Drreamer/ColorInterfaceBinding如果它在您的项目中不起作用,请澄清在这种情况下提出的例外情况。这有助于找到问题的确切原因。