Search code examples
c#wpfbindinganchorrelativesource

How to binding other element in ToolTip


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.


Solution

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