【问题标题】:Bind to Ancestor in Property sett在属性设置中绑定到祖先
【发布时间】: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 中执行RelativeSource Binding。如果您调试您的应用程序,Visual Studio 中的输出窗口将显示您的绑定错误,这应该可以帮助您找到错误的根源。
  • @abe 是的,我知道 - 所以我找到了问题(但没有解决方案)。在第一种情况下,绑定就像一个魅力。在第二种情况下,VS 显示“没有找到类型的祖先”正如我在对 Sheridan 的回答中所写的那样,我猜(完全不确定)WPF 尝试(如果在 setter 中使用)来解决绑定 - 而当我使用它直接在模板中它在项目位于项目控件内时解析绑定,这(当然)有效

标签: wpf binding


【解决方案1】:

您似乎在声明 AncestorType 时出错了...请参阅此示例:

<Button Foreground="Blue" Background="Red">
    <Rectangle Margin="20" Width="50" Height="50">
        <Rectangle.Style>
            <Style>
                <Setter Property="Rectangle.Fill" Value="{Binding Foreground, 
                    RelativeSource={RelativeSource Mode=FindAncestor, 
                    AncestorType={x:Type Button}}}" />
            </Style>
        </Rectangle.Style>
    </Rectangle>
</Button>

【讨论】:

  • 您可能已经注意到 - 在我的第一个示例(模板)中,此绑定有效。因此,祖先发现通常有效。我猜,如果在 setter 中使用,WPF 会尝试分配绑定的值 - 此时项目控件被创建并且没有父项。
猜你喜欢
  • 1970-01-01
  • 2011-03-25
  • 2011-01-05
  • 2011-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-10
  • 1970-01-01
相关资源
最近更新 更多