#377 – Reuse Tooltips by Defining Them as Resources

Because tooltips are instances of the Tooltip control, you can create tooltip instances in a resource dictionary and then reuse them for multiple controls.

Below is an example of a tooltip that uses data binding to display the full text of a TextBox control.

    <Window.Resources>
        <!-- Standard tooltip for TextBox controls, displays Text property of parent control in a TextBlock -->
        <ToolTip x:Key="textBlockTooltip" DataContext="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}">
            <StackPanel>
                <Label FontWeight="Bold" Content="Full Text"/>
                <TextBlock Text="{Binding Text}" TextWrapping="Wrap" Width="200"/>
            </StackPanel>
        </ToolTip>
    </Window.Resources>

We can then use this tooltip on any TextBox control.

        <TextBox Text="Now is the winter of our discontent etc"
            Width="100" Margin="10" ToolTip="{StaticResource textBlockTooltip}"/>
        <TextBox Text="All the world's a stage etc"
            Width="100" Margin="10" ToolTip="{StaticResource textBlockTooltip}"/>


Advertisement