将触发器内的设置器值绑定到元素

时间:2018-11-05 08:18:35

标签: c# wpf xaml data-binding

我想在Expander关闭时给其不同的标头。当该值恒定时,一切正常,但是当我尝试将标头绑定到控件中的DP(例如Presenter)时,它将无法正常工作。这是我的简化标记:

<UserControl x:Class="MyProject.Views.PlanDisplayer"
             xmlns=...
             xmlns:local="clr-namespace:MyProject.Views"
             x:Name="This">
    <Grid>
        ...
        <Expander>
            <Expander.Style>
                <Style TargetType="Expander" BasedOn="{StaticResource ResourceKey=ChildExpanderStyle}">
                    <Setter Property="Header">
                        <Setter.Value>
                            <!--Works-->
                            <TextBlock Text="{Binding ElementName=This, Path=Presenter.Walls.Count, StringFormat='Walls:  [{0}]'}"/>
                        </Setter.Value>
                    </Setter>
                    <Style.Triggers>
                        <Trigger Property="IsExpanded" Value="False">
                            <Setter Property="Header">
                                <Setter.Value>
                                    <!--Doesn't work → Error: 4 : Cannot find source for binding-->
                                    <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=local:PlanDisplayer, Mode=FindAncestor}, Path=Presenter.Walls.Count, StringFormat='Walls  [{0}]'}"/>
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Expander.Style>

            ...
        </Expander>
    </Grid>
</UserControl>

1 个答案:

答案 0 :(得分:1)

尝试使用相同的TextBlock并对其应用Style

<Style TargetType="Expander">
    <Setter Property="Header">
        <Setter.Value>
            <TextBlock>
                <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Setter Property="Text" Value="{Binding ElementName=This, Path=Presenter.Walls.Count, StringFormat='Walls:  [{0}]'}}" />
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding IsExpanded, RelativeSource={RelativeSource AncestorType=Expander}}" Value="True">
                                <Setter Property="Text" Value="{Binding Path=Presenter.Walls.Count, StringFormat='Walls  [{0}]'}, RelativeSource={RelativeSource AncestorType=UserControl}}" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>
        </Setter.Value>
    </Setter>
</Style>