Question

this code work correct:

   <UserControl x:Class="Extended.InputControls.TextBoxUserControl" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="clr-namespace:Extended.InputControls">
        <TextBox x:Name="textBox"
            ToolTip="{Binding Path=CustomToolTip,RelativeSource={RelativeSource AncestorType=local:TextBoxUserControl}}"/>
</UserControl>

but this code Does not work!!!

<UserControl x:Class="Extended.InputControls.TextBoxUserControl" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="clr-namespace:Extended.InputControls">
        <TextBox x:Name="textBox">
            <TextBox.ToolTip>
                <ToolTip Text="{Binding Path=CustomToolTip,RelativeSource={RelativeSource AncestorType=local:TextBoxUserControl}}" Background="Yellow"/>
            </TextBox.ToolTip>
        </TextBox>
</UserControl>

i need create custom tooltip and bind it to CustomToolTip but in second code that's not bind to anything where is the problem?

Was it helpful?

Solution

First of all, if we're talking WPF here, it should be <ToolTip Content="..."> instead of <ToolTip Text="...">, since ToolTip has no Text property.

Regarding the binding: Binding to other elements in the user control from within a ToolTip doesn't work since ToolTip elements are not part of the visual tree, as explained in another question that also provides one potential solution.

However, it seems that you're binding to some property defined in the UserControl's code-behind? In that case it's even easier to solve by setting the UserControl's DataContext to the control itself:

<UserControl x:Class="Extended.InputControls.TextBoxUserControl" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:Extended.InputControls"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <TextBox x:Name="textBox">
        <TextBox.ToolTip>
            <ToolTip Content="{Binding CustomToolTip}" Background="Yellow"/>
        </TextBox.ToolTip>
    </TextBox>
</UserControl>

Alternatively, you could also set the DataContext in code-behind:

public TextBoxUserControl()
{
    this.DataContext = this;
    InitializeComponent();
}

In both cases, the CustomToolTip property can be accessed directly without the need for a RelativeSource binding.

An even better solution would be to introduce come kind of Viewmodel class that holds the CustomToolTip and all similar properties, and set this class as the UserControl's DataContext.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top