WPF Tooltip Show only when Text is something
.net, c#, vb.net, wpf
Solution
You can consider using a IValueConverter to show/hide the tooltip border. Add this class to your project :
class BorderVisibilitySetter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//check if the control's content property is null or empty
if(value == null || value.ToString() == string.Empty)
return Visibility.Collapsed;
else
return Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Then modify your xaml as :
<src:BorderVisibilitySetter x:Key="BorderVisible" />
<Style x:Key="{x:Type ToolTip}" TargetType="{x:Type ToolTip}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToolTip}">
<Border Background="Black" Visibility="{TemplateBinding Content, Converter={StaticResource BorderVisible}}" >
<TextBlock FontFamily="Tahoma" FontSize="11" Text="{TemplateBinding Content}" Foreground="WhiteSmoke" Padding="2" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Problem
i am having the following code: ``` <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Style x:Key="{x:Type ToolTip}" TargetType="{x:Type ToolTip}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ToolTip}"> <Border Background="Black"> <TextBlock FontFamily="Tahoma" FontSize="11" Text="{TemplateBinding Content}" Foreground="WhiteSmoke" Padding="2" /> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <StackPanel> <Label Content="Label 1" ToolTip="asd" /> <Label Content="Label 2" ToolTip="" /> <TextBlock Text="TextBlock 1" ToolTip="asd" /> <TextBlock Text="TextBlock 2" ToolTip="" /> <Button Content="Button 1" ToolTip="asd" /> <Button Content="Button 2" ToolTip="" /> </StackPanel> ``` Now, as you can see by testing that when you hover over Label 2, Textblock 2, Button 2, a tooltip still shows. I want that to be triggered that if Tooltip is empty or null then it should not show anything. I know i can simply remove that from XAML But the way i am doing here is something different. I have tried adding a trigger to check value ="" and to null and inside trigger, setting template to null but none of them is working If some of you experts could shed some light on it, i would be very glad