How to binding other element in ToolTip

2.2k views Asked by At

I want binding Text in Tooltip but i have one problem, it is binding value is other element controls, therefore i cannot basically get their value through binding.

<TextBlock x:Name="txb2" Text="Hello Stackoverflow"/>

<TextBox Grid.Row="1" TextChanged="TextBox_TextChanged">
    <TextBox.ToolTip>
        <TextBlock>
            <Run Text="{Binding ElementName=txb2, Path=Text}" FontWeight="Bold"/>
        </TextBlock>
    </TextBox.ToolTip>
</TextBox>

basically I tried binding this code.

2

There are 2 answers

2
Access Denied On BEST ANSWER

If you look at the output you will see an error:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=txb2'. BindingExpression:Path=Text; DataItem=null; target element is 'Run' (HashCode=58577354); target property is 'Text' (type 'String')

You can fix it by using x:Reference:

<TextBlock x:Name="txb2" Text="Hello Stackoverflow"/>

<TextBox Grid.Row="1">
    <TextBox.ToolTip>
        <TextBlock>
            <Run Text="{Binding Source={x:Reference txb2}, Path=Text}" FontWeight="Bold"/>
        </TextBlock>
    </TextBox.ToolTip>
</TextBox>

As for the difference between ElementName and x:Reference take a look at the following thread. ElementName does not work since Tooltip is not a Ui property, but ElementName only works with Ui Element hierarchy (Visual Tree) when it searches txb2.

1
Peregrine On

Tooltips exist outside the visual tree, so can't reference other controls by name. All that a tooltip knows about is its own PlacementTarget – the UIElement that it is displayed against.

One way to allow the tooltip to reference other controls is to hijack some otherwise unused property of this placement target control (Tag is most often suitable), which can then be referenced by the tooltip.

<TextBox x:Name="txb2" Text="Hello Stackoverflow" Width="200" />

<TextBox Grid.Row="1" Tag="{Binding ElementName=txb2}" Width="200">
    <TextBox.ToolTip>
        <ToolTip DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
            <TextBlock>
                <Run Text="{Binding Text}" FontWeight="Bold" />
            </TextBlock>
         </ToolTip>
    </TextBox.ToolTip>
</TextBox>

if you're using the MVVM design pattern, an alternative method (that doesn't require property hijacking) is to bind to the PlacementTarget's DataContext (usually the ViewModel). You can then bind the tooltip's content to whatever property of that you like.

<ToolTip DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
    ....