WPF ToolTip ExampleThis WPF example uses the ToolTip attribute and the ToolTipOpening event. It has an example screenshot.
A ToolTip appears when the mouse hovers over a control. It is meant to provide information about the control. In WPF, we use the ToolTip attribute and the ToolTipOpening event to create ToolTips.
This example markup has a Button control. You can add this by dragging it from the Toolbox to the window, where it nests within the Grid. I added a ToolTip attribute. With this attribute, we can set static ToolTip strings.
And: The ToolTip string is displayed when the user hovers over the control. Many controls, not just buttons, can have ToolTips.
Also: I added the ToolTipOpening event handler. In the Button_ToolTipOpening method, we dynamically set the content of the ToolTip.
Cast: In Button_ToolTipOpening, we cast the sender object to a Button type. Then we set the ToolTip of the Button.As
Tip: The opening event occurs right before the ToolTip is displayed. So we change its value right when needed.
Example markup: XAML
Title="MainWindow" Height="350" Width="525">
<Button Content="Button" HorizontalAlignment="Left" Margin="10,10,0,0"
Example code: C#
public partial class MainWindow : Window
private void Button_ToolTipOpening(object sender, ToolTipEventArgs e)
// ... Set ToolTip on Button before it is shown.
Button b = sender as Button;
b.ToolTip = DateTime.Now.ToShortTimeString();
The example does not show this, but usually a ToolTip is just a static property. So just set the ToolTip property in your XAML. Programs less often need to set ToolTips dynamically.
Note: A program can use a default ToolTip property, and only change it when needed in ToolTipOpening (or another event handler).
Also, a ToolTipClosing event is available. This occurs (obviously) when the ToolTip goes away. As with the ToolTipOpening event handler, or any event handler, you can run arbitrary interface code here.
Summary. They are an essential part of many interfaces. And ToolTips in WPF are easy to add, change, and even manipulate in a dynamic way with C# code. There is more complexity to them than shown here, but this example covers the basics.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.