工具提示、信息提示或提示 - 各种名称,但概念保持不变:通过将鼠标悬停在特定控件或链接上,可以获得有关特定控件或链接的相关信息的提示。WPF 显然也支持这个概念,并且通过使用在FrameworkElement类中找到的ToolTip属性 ,几乎所有 WPF 控件都继承自该类。
为控件指定工具提示非常简单,您将在第一个非常基本的示例中看到:
<Window x:Class="WpfTutorialSamples.Control_concepts.ToolTipsSimpleSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ToolTipsSimpleSample" Height="150" Width="400">
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
<Button ToolTip="Click here and something will happen!">Click here!</Button>
</Grid>
</Window>
正如您在屏幕截图中看到的那样,一旦鼠标悬停在按钮上,就会产生一个带有指定字符串的浮动框。这是大多数 UI 框架所提供的 - 文本字符串的显示,仅此而已。
但是,在 WPF 中,ToolTip属性实际上不是字符串类型,而是对象类型,这意味着我们可以在其中放入任何我们想要的内容。这开辟了一些非常酷的可能性,我们可以为用户提供更丰富、更有用的工具提示。例如,考虑这个例子并将其与第一个进行比较:
<Window x:Class="WpfTutorialSamples.Control_concepts.ToolTipsAdvancedSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ToolTipsAdvancedSample" Height="200" Width="400" UseLayoutRounding="True">
<DockPanel>
<ToolBar DockPanel.Dock="Top">
<Button ToolTip="Create a new file">
<Button.Content>
<Image Source="/WpfTutorialSamples;component/Images/page_white.png" Width="16" Height="16" />
</Button.Content>
</Button>
<Button>
<Button.Content>
<Image Source="/WpfTutorialSamples;component/Images/folder.png" Width="16" Height="16" />
</Button.Content>
<Button.ToolTip>
<StackPanel>
<TextBlock FontWeight="Bold" FontSize="14" Margin="0,0,0,5">Open file</TextBlock>
<TextBlock>
Search your computer or local network
<LineBreak />
for a file and open it for editing.
</TextBlock>
<Border BorderBrush="Silver" BorderThickness="0,1,0,0" Margin="0,8" />
<WrapPanel>
<Image Source="/WpfTutorialSamples;component/Images/help.png" Margin="0,0,5,0" />
<TextBlock FontStyle="Italic">Press F1 for more help</TextBlock>
</WrapPanel>
</StackPanel>
</Button.ToolTip>
</Button>
</ToolBar>
<TextBox>
Editor area...
</TextBox>
</DockPanel>
</Window>
请注意此示例如何为第一个按钮使用简单的字符串工具提示,然后为第二个按钮使用更高级的工具提示。在高级情况下,我们使用面板作为根控件,然后我们可以随意添加控件。结果非常酷,带有标题、描述文本和提示,您可以按 F1 获取更多帮助,包括帮助图标。
高级选项
ToolTipService 类有一堆有趣的属性,它们会影响工具提示的行为。您可以直接在具有工具提示的控件上设置它们,例如,我们使用ShowDuration属性延长工具提示显示的时间(我们将其设置为 5.000 毫秒或 5 秒):
<Button ToolTip="Create a new file" ToolTipService.ShowDuration="5000" Content="Open" />
您还可以控制弹出是否应该有阴影,使用HasDropShadow财产,还是提示应使用被显示为残疾控制以及,ShowOnDisabled财产。还有其他几个有趣的属性
概括
工具提示对用户有很大帮助,在 WPF 中,它们既易于使用又极其灵活。将您可以完全控制工具提示的设计和内容这一事实与ToolTipService类的属性相结合,在您的应用程序中创建更用户友好的内联帮助。