Search code examples
wpfwpf-controlstooltip

Common Tooltip style in WPF


Can I make a tooltip style which can be applied to all tooltips for every control?

I tried this but I cant get the content (Tooltip text) in style, it is showing empty text in tooltip:

<Style TargetType="{x:Type ToolTip}" >
        <Setter Property="OverridesDefaultStyle" Value="true" />
        <Setter Property="HasDropShadow" Value="True" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="FontSize" Value="12" />
        <Setter Property="Placement" Value="Bottom" />
        <Setter Property="VerticalOffset" Value="0" />
        <Setter Property="Padding" Value="8" />

        <Setter Property="HorizontalContentAlignment" Value="Center" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ToolTip}" >
                    <StackPanel Margin="7,1" >
                      <Border Background="#FFF7F7CC" CornerRadius="1" >
                            <TextBlock Margin="1" Foreground="Black" HorizontalAlignment="Center" VerticalAlignment="Top" Text="{TemplateBinding ToolTip}"/>
                        </Border>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

For Using this style I have to put a seperate Tooltip tag in control, eg to apply tooltip to border,

<Border>
    <Border.ToolTip>
          <ToolTip ToolTip="This is tooltip text"  />
    </Border.ToolTip>
........
.........
</Border>

but is there any way where tooltipstyle applies to all control with tooltip mentioned in same tag. eg.

<Border BorderBrush="Transparent" Background="Transparent" Cursor="Help" ToolTip="This is Tooltip" >
.....
.....
</Border>

let me know if any further details are required. Thanks in Anticipation.


Solution

  • Yes Your approach will work. But a small change is needed in the Control Template. Replace the TextBlock with ContentPresenter.

                    <ControlTemplate TargetType="{x:Type ToolTip}" >
                        <StackPanel Margin="7,1" >
                            <Border Background="#FFF7F7CC" CornerRadius="1" >
                            <ContentPresenter Margin="1" HorizontalAlignment="Center" VerticalAlignment="Top" />
                            </Border>
                        </StackPanel>
                    </ControlTemplate>