Jakub Pawlinski
Jakub Pawlinski

Reputation: 482

wpf tooltips add additional string across application

Similar to this but more complicated.

I need to override all tooltips (and all controls that can have one but not have it now) with additional information about this control. I wanted to put something like

sender.ToolTip =+ "\n\r" + sender.Name + "(" + sender.Tag + ")";

but googled a bit about that with no success.


UPDATE

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.ToolTipOpeningEvent, new RoutedEventHandler((s, e2) =>
        {
            var fe = s as FrameworkElement;
            fe.ToolTip = fe.ToolTip + "\n\r(" + fe.Name + ")";
            //fe.Name + " " + fe.Tag;
        }));

        new MainWindow();
    }

nearly works, but:


updated with eliminated null exception and protected from duplicate entries

            EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.ToolTipOpeningEvent, new RoutedEventHandler((s, e2) =>
        {
            var fe = (FrameworkElement)s;

            //skip already updated tooltips
            if (fe.ToolTip.ToString().Contains(fe.Name)) return;

            //update tooltip value
            fe.ToolTip = (fe.ToolTip + Environment.NewLine + "(" + ( fe.Tag != null 
                ? string.Join(": ", fe.Name, fe.Tag) 
                : fe.Name
            ) +  ")").Trim();
        }));

Still no idea how to override components without tooltip - maybe I could assing "" tooltip to all buttons and other types of controls and than update those which are configured?

thanks

Upvotes: 1

Views: 181

Answers (1)

Jarek Kardas
Jarek Kardas

Reputation: 8455

Czesc!

You can use Routed Events infrastructure available in WPF to do this.

Call EventManager.RegisterClassHandler method like this:

EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.ToolTipOpeningEvent, new RoutedEventHandler((s, e) =>
            {
                var fe = s as FrameworkElement;
                fe.ToolTip = fe.Name + " " + fe.Tag;                
            }));

You can add this code to App.xaml.cs under the constructor:

protected override void OnStartup(StartupEventArgs e) 
{ 
    base.OnStartup(e); 
    <code goes here> 
}

Upvotes: 2

Related Questions