wpfxamldata-bindingwindowrelativesource

Binding to the Title of a Window does not always work


I need to databind two TextBlocks to the Window.Title property. The first one works via:

RelativeSource FindAncestor, AncestorType=Window}"

But the second one does not (it's deeply nested within a button ToolTip).

How can I change the second one to make it also display the Title of the Window?

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

Solution

  • The tool tip is displayed in a popup and is not part of the same visual tree as the button or your window. Consequently, RelativeSource and ElementName bindings do not work.

    What you can do is bind the window title to the Tag property of your button and then bind the Text of the tool tip TextBlock to the Tag property of the PlacementTarget (which is the button).

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