0

I content control "MyControl" and this has a property "GlobalBackground". For the items I have a style like this.

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

This works as expected.

Now I want to use the same template bound to different properties of the Itemscontrol. So the idea is to set a property via setter (Style Triggers) When I do this

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

the binding fails.

Is there no way to use FindAncestor bindings in a style setter or am I just doing something wrong?

Manfred

4

1 回答 1

0

您似乎在声明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>
于 2013-08-06T14:45:13.343 回答