2013-08-06 184 views
0

我的内容控制“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的不同属性的相同模板。 这样的想法是设置通过二传手(风格触发器) 一个属性当我这样做

<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绑定或我只是做错了什么?

曼弗雷德

+0

你绝对可以做一个''RelativeSource' Binding'。如果你调试你的应用程序,Visual Studio中的输出窗口会显示你的绑定错误,这应该可以帮助你找到错误的底部。 –

+0

@abe 是的,我知道 - 所以我找到了问题(但没有解决方案)。 在第一种情况下,绑定就像一个魅力。 在第二种情况VS显示“无祖先的类型..发现” 正如我在我对谢里登的答案中写道,我猜测(不确定所有)WPF尝试(如果用在setter中)解析绑定 - 而当我直接在模板中使用它,它解决了项目在项目控件内部的绑定,至少(当然)可以工作 – ManniAT

回答

0

你似乎已经犯了一个错误,宣布AncestorType ......看到这个例子:在`Style`

<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> 
+0

正如您可能已经注意到的那样 - 在我的第一个示例(模板)中,此绑定起作用。 所以祖先的发现一般工作。 我想,WPF会尝试分配绑定的值(如果在setter中使用的话) - 此时项目控件已创建并且没有父项。 – ManniAT