我正在编写一个WPF应用程序,其中包含许多不同的控件,每个控件都有自己的工具提示。虽然这些工具提示很有用,但其中一些相当长,会妨碍视线。
我想创建一个按钮,当单击该按钮时,可以启用和禁用应用程序中的所有工具提示。我一直在努力寻找一种看起来非常冗长和不必要的方法。是否有一种快速完成我想要的功能的方法?
我想创建一个按钮,当单击该按钮时,可以启用和禁用应用程序中的所有工具提示。我一直在努力寻找一种看起来非常冗长和不必要的方法。是否有一种快速完成我想要的功能的方法?
ToolTip
的Visbility
属性设置为Collapsed
。示例代码如下:private bool _isToolTipVisible = true;
private void Button_Click(object sender, RoutedEventArgs e)
{
Style style = new Style(typeof(ToolTip));
style.Setters.Add(new Setter(UIElement.VisibilityProperty, Visibility.Collapsed));
style.Seal();
foreach (Window window in Application.Current.Windows)
{
if (_isToolTipVisible)
{
window.Resources.Add(typeof(ToolTip), style); //hide
_isToolTipVisible = false;
}
else
{
window.Resources.Remove(typeof(ToolTip)); //show
_isToolTipVisible = true;
}
}
}
<Application.Resources>
<Style TargetType="{x:Type ToolTip}">
<Setter Property="Template" Value="{x:Null}" />
</Style>
</Application.Resources>
Style _style;
void Button_Click(object sender, RoutedEventArgs e)
{
if (_style == null)
{
_style = (Style)Application.Current.Resources[typeof(ToolTip)];
Application.Current.Resources.Remove(typeof(ToolTip));
}
else
Application.Current.Resources.Add(typeof(ToolTip), _style);
}
<Style x:Key="{x:Type ToolTip}" TargetType="ToolTip">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToolTip">
<Border Name="Border" BorderThickness="1" Background="PaleGoldenrod" CornerRadius="4" BorderBrush="Black">
<ContentPresenter Margin="4"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
... various other settings
</Style>
<Style x:Key="NoTip" TargetType="ToolTip">
<Setter Property="Visibility" Value="Collapsed"/>
</Style>
private Style styleWithTips;
private Style styleNoTips;
...
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Set initial tips on/off
styleWithTips = (Style)Application.Current.Resources[typeof(ToolTip)];
styleNoTips = (Style)Application.Current.Resources["NoTip"];
updateTipStyle();
}
private void Settings_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "ShowHints")
{
updateTipStyle();
}
}
...
private void updateTipStyle()
{
ResourceDictionary resources = Application.Current.Resources;
bool showHints = Properties.Settings.Default.ShowHints;
if (resources.Contains(typeof(ToolTip)))
{
resources.Remove(typeof(ToolTip));
}
resources.Add(typeof(ToolTip), showHints ? styleWithTips: styleNoTips);
}
window.Resources.Add(typeof(ToolTip), style); //hide
。 - Stavrosforeach
循环,然后将window
替换为this
,这样我就能够切换工具提示了。非常感谢!! - Stavros