【发布时间】:2013-08-06 14:31:38
【问题描述】:
我的内容控件“MyControl”,它有一个属性“GlobalBackground”。 对于我有这样的风格的项目。
<ControlTemplate x:Key="XTemplate" TargetType="{x:Type local:MyControlItem}">
<Grid HorizontalAlignment="Stretch">
<Rectangle Height="2" Fill="{Binding GlobalBackground, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=local:MyControl}}"/>
...
</Grid>
</ControlTemplate>
<Style x:Key="XStyle" TargetType="{x:Type local:MyControlItem}">
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template" Value="{StaticResource XTemplate}"/>
</Style>
这按预期工作。
现在我想使用绑定到 Itemscontrol 不同属性的同一个模板。 所以想法是通过setter(样式触发器)设置一个属性 当我这样做时
<ControlTemplate x:Key="XTemplate" TargetType="{x:Type local:MyControlItem}">
<Grid HorizontalAlignment="Stretch">
<Rectangle Height="2" Fill="{TemplateBinding Background}"/>
...
</Grid>
</ControlTemplate>
<Style x:Key="XStyle" TargetType="{x:Type local:MyControlItem}">
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Background" Value="{Binding GlobalBackground, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=local:MyControl}}" />
<Setter Property="Template" Value="{StaticResource XTemplate}"/>
</Style>
绑定失败。
有没有办法在样式设置器中使用 FindAncestor 绑定,或者我只是做错了什么?
曼弗雷德
【问题讨论】:
-
您绝对可以在
Style中执行RelativeSourceBinding。如果您调试您的应用程序,Visual Studio 中的输出窗口将显示您的绑定错误,这应该可以帮助您找到错误的根源。 -
@abe 是的,我知道 - 所以我找到了问题(但没有解决方案)。在第一种情况下,绑定就像一个魅力。在第二种情况下,VS 显示“没有找到类型的祖先”正如我在对 Sheridan 的回答中所写的那样,我猜(完全不确定)WPF 尝试(如果在 setter 中使用)来解决绑定 - 而当我使用它直接在模板中它在项目位于项目控件内时解析绑定,这(当然)有效