【问题标题】:Binding to the Title of a Window does not always work绑定到窗口的标题并不总是有效
【发布时间】:2024-04-22 17:50:01
【问题描述】:

我需要将两个TextBlocks 数据绑定到Window.Title 属性。第一个通过:

RelativeSource FindAncestor, AncestorType=Window}"

但第二个没有(它深深嵌套在一个按钮 ToolTip 中)。

如何更改第二个以使其也显示WindowTitle

<Window ...>
   <Border ...>
      <Grid ...>
         <Grid ...>
            <!-- TEXTBLOCK BELOW WORKS -->
            <TextBlock Grid.Column="2" Text="{Binding Title, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"
                       HorizontalAlignment="Stretch" VerticalAlignment="Center" Foreground="White" FontSize="18px" FontStretch="UltraExpanded" />
            <Button Grid.Column="3" HorizontalAlignment="Right" VerticalAlignment="Stretch"
                    Background="Transparent" BorderBrush="Transparent" Foreground="Transparent"
                    ToolTipService.InitialShowDelay="0" ToolTipService.BetweenShowDelay="0" ToolTipService.ShowDuration="60000">
               <Button.ToolTip>
                  <ToolTip x:Name="helpButtonTooltip" Width="240" ToolTipService.InitialShowDelay="0">
                     <!-- TEXTBLOCK BELOW DOES NOT WORK; HOW CAN I MAKE IT WORK? -->
                     <TextBlock Text="{Binding Title, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"
                                HorizontalAlignment="Stretch" VerticalAlignment="Center" Foreground="White" FontSize="18px" FontStretch="UltraExpanded" />

【问题讨论】:

    标签: wpf xaml data-binding window relativesource


    【解决方案1】:

    工具提示显示在弹出窗口中,与按钮或窗口不属于同一可视树。因此,RelativeSourceElementName 绑定不起作用。

    您可以做的是将窗口标题绑定到按钮的Tag 属性,然后将工具提示TextBlockText 绑定到PlacementTargetTag 属性(即按钮)。

    <Button Tag="{Binding Title, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}">
       <Button.ToolTip>
          <ToolTip>
             <TextBlock Text="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource AncestorType={x:Type ToolTip}}}"/>
          </ToolTip>
       </Button.ToolTip>
    </Button>
    

    【讨论】: