如何在WPF中的代码背后显示工具提示 [英] How to show tooltip in code behind in WPF
问题描述
如何在代码隐藏中显示工具提示?下面的代码更好地定义了我的问题.显然,我不希望代码检查鼠标位置等,而只是如何显示工具提示.
How can I show a tooltip in code-behind? The code below defines my question better. Obviously I don't want the code to check for mouse position etc, just how to display the tooltip.
private void UIElement_OnMouseMove(object sender, MouseEventArgs e)
{
// if mouse position equals certain coordinates show the tooltip
}
推荐答案
尝试如下:
if (control.ToolTip != null)
{
// Main condition
if (control.ToolTip is ToolTip)
{
var castToolTip = (ToolTip)control.ToolTip;
castToolTip.IsOpen = true;
}
else
{
toolTip.Content = control.ToolTip;
toolTip.StaysOpen = false;
toolTip.IsOpen = true;
}
}
必要的主要条件
,因为可以通过两种方法设置用于控制的 ToolTip
:
The Main condition
necessary, because ToolTip
for Control can be set in two approaches:
第一种方法
First approach
<Button Name="TestButton"
ToolTip="TestToolTip" />
这种方法是最常见的.在这种情况下,ToolTip的内容将成为对象,而不是 ToolTip
的类型.
This approach is most common. In this case, the content of the ToolTip will object and not type of ToolTip
.
第二种方法
Second approach
<Button Name="TestButton"
Content="Test">
<Button.ToolTip>
<ToolTip>TestToolTip</ToolTip>
</Button.ToolTip>
</Button>
与此相同:
<Button Name="TestButton"
Content="Test">
<Button.ToolTip>
TestToolTip
</Button.ToolTip>
</Button>
在这种情况下,工具提示的内容类型将为 Tooltip
.请注意,在第二种情况下,对象会自动在 TestToolTip
行上填充ToolTip对象,因此此方法的工作速度会变慢.
In this case, the Content type of ToolTip will be Tooltip
. Note that in the second case, the object automatically fills ToolTip object on line TestToolTip
, hence this approach will work a bit slower.
因此,当我们尝试在此处将 ToolTip
类型的内容分配给ToolTip时,需要进行此检查以避免出现异常:
Therefore, this check is needed to avoid an exception when we try to assign to the ToolTip the content of the ToolTip
type here:
toolTip.Content = control.ToolTip;
下面是一个完整的示例:
Below is a full example:
XAML
<Grid>
<Button Name="TestButton"
Width="100"
Height="25"
Content="Test"
ToolTip="TestToolTip" />
<Button Name="ShowToolTip"
VerticalAlignment="Top"
Content="ShowToolTip"
Click="ShowToolTip_Click" />
</Grid>
隐藏代码
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ShowToolTip_Click(object sender, RoutedEventArgs e)
{
var toolTip = new ToolTip();
if (TestButton.ToolTip != null)
{
if (TestButton.ToolTip is ToolTip)
{
var castToolTip = (ToolTip)TestButton.ToolTip;
castToolTip.IsOpen = true;
}
else
{
toolTip.Content = TestButton.ToolTip;
toolTip.StaysOpen = false;
toolTip.IsOpen = true;
}
}
}
}
这篇关于如何在WPF中的代码背后显示工具提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!