Ali Akber
Ali Akber

Reputation: 3800

How to set the font of a ToolTip same as parent control in WPF C#

I have a number of fields where different fonts are used. When I hover the mouse over a field, it's always showing the ToolTip with a default font.
But I want to set the ToolTip font same as the field over which I'm hovering my mouse.
How can I do this?

Here is the style of the ToolTip:

    <Style TargetType="ToolTip">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Text="{Binding}"
                               MaxWidth="400"
                               TextWrapping='Wrap' />
                </DataTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="Content" Value="{x:Static sys:String.Empty}">
                <Setter Property="Visibility" Value="Collapsed" />
            </Trigger>
            <Trigger Property="Content" Value="{x:Null}">
                <Setter Property="Visibility" Value="Collapsed" />
            </Trigger>
        </Style.Triggers>
    </Style>

Here is the XAML of the main content:

    <TextBox Text="Hello there!"
             FontFamily="Cambria"
             ToolTip="{Binding Text, RelativeSource={RelativeSource Self}}" />

Upvotes: 1

Views: 1562

Answers (3)

Dominic Jonas
Dominic Jonas

Reputation: 5005

This method is working and generic:

    <Style TargetType="ToolTip">
        <Setter Property="FontFamily" Value="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.FontFamily}"/>
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Text="{Binding}"
                           MaxWidth="400"
                           TextWrapping='Wrap' />
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Preview

Preview

Upvotes: 2

ASh
ASh

Reputation: 35681

ToolTip has PlacementTarget property (The UIElement that is the logical parent of the ToolTip control (TextBox, TextBlock, whatever)). Create FontFamily binding to PlacementTarget.FontFamily

<Setter Property="ContentTemplate">
    <Setter.Value>
        <DataTemplate>
            <TextBlock Text="{Binding}"
                       FontFamily="{Binding RelativeSource={RelativeSource AncestorType=ToolTip}, Path=PlacementTarget.FontFamily}"
                       MaxWidth="400"
                       TextWrapping='Wrap' />
        </DataTemplate>
    </Setter.Value>
</Setter>

Upvotes: 4

Andrey Alonzov
Andrey Alonzov

Reputation: 357

You can use this code but it will work only for TextBox.

<DataTemplate>
    <TextBlock Text="{Binding}"
        MaxWidth="400"
        FontFamily="{Binding FontFamily, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TextBox}}}"
        TextWrapping='Wrap' />
</DataTemplate>

Upvotes: 0

Related Questions