A ToolTip is a pop-up window that displays some information in a small window. The XAML Tooltip element represents a window tooltip that can be attached a WPF control using its ToolTip property. This article shows how to use a ToolTip control in WPF.
Creating a ToolTip
The ToolTip element represents a ToolTip control in XAML.
The IsOpen property indicates whether or not a ToolTip is visible. The HorizontalOffset and VerticalOffset properties represent the horizontal and vertical distance between the target control and the pop-up window. The Content property represents the contents of the ToolTip.
The code snippet in Listing 1 creates a ToolTip control and sets the horizontal offset, vertical offset and content of a ToolTip control.
- <ToolTip Content="Hello! I am a ToolTip."
- HorizontalOffset="10" VerticalOffset="20"/>
Listing 1.
The output looks as in Figure 1.
Figure 1.
ToolTip Service
To display a tooltip for a control, the ToolTipService class must be used. The SetToolTip and GetToolTip static methods are used to set and get the tooltip of a control.
The following code snippet creates a ToolTipService.ToolTip for a control.
- <ToolTipService.ToolTip >
- <ToolTip Content="Hello! I am a ToolTip."
- HorizontalOffset="10" VerticalOffset="20"/>
- </ToolTipService.ToolTip>
Listing 2.
The code snippet in Listing 3 sets a ToolTip of a Button control.
- <Button Content="Mouse over me" Width="150" Height="30"
- Canvas.Top="10" Canvas.Left="10">
- <ToolTipService.ToolTip >
- <ToolTip Content="Hello! I am a ToolTip."
- HorizontalOffset="10" VerticalOffset="20"/>
- </ToolTipService.ToolTip>
- </Button>
Listing 3.
Then if you run the application and hover the mouse over the button control, the output looks as in Figure 2.
Figure 2.
WPF ToolTip with Image
The ToolTip content can be any control and multiple controls.
The code snippet in Listing 4 creates a ToolTip with an image and text in it.
-
- <Button Content="Mouse over me" Width="150" Height="30"
- Canvas.Top="50" Canvas.Left="20">
-
- <ToolTipService.ToolTip >
- <ToolTip HorizontalOffset="0" VerticalOffset="0">
-
- <StackPanel Width="250" Height="150">
-
- <StackPanel.Background>
- <ImageBrush ImageSource="Garden.jpg"
- Opacity="0.4"/>
- </StackPanel.Background>
-
- <TextBlock >
- <Run Text="This is a tooltip with an image and text"
- FontFamily="Georgia" FontSize="14" Foreground="Blue"/>
- </TextBlock>
- </StackPanel>
- </ToolTip>
- </ToolTipService.ToolTip>
- </Button>
Listing 4.
The new tooltip looks as in Figure 3.
Figure 3.
Using the previous approach, you can pretty much put any content as a ToolTip popup.
Summary
In this article, I discussed how to add a tooltip to a control in WPF using XAML.