“Intercept” the opening of any tooltip appwide

2019-04-27 07:49发布

问题:

I want to show the text of a tooltip of any control in my wpf app inside a status bar, when a tooltip is about to be opened.

Of course I could try to loop recursively through all child controls of the main window and set their ToolTipOpening event to always the same method. But is there an easier way ?

Something like a Application.Current.AnyToolTipOpening event ?

回答1:

Sure, try this:

EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.ToolTipOpeningEvent, new ToolTipEventHandler(ToolTipHandler));

That registers a handler for all classes that derive from FrameworkElement.

Your handler method might look like this:

   private void ToolTipHandler(object sender, ToolTipEventArgs e) {
        // To stop the tooltip from appearing, mark the event as handled
        e.Handled = true; 
        FrameworkElement source = e.Source as FrameworkElement; 
        if (source != null) {
            MessageBox.Show(source.ToolTip.ToString()); // or whatever you like
        }
    }


回答2:

thanks , that worked. Additionally,to make the statusbar text disappear when the mouse leaves the control with the tooltip :

 EventManager.RegisterClassHandler(typeof(FrameworkElement),
                  MouseLeaveEvent, new MouseEventHandler(ClearText));


标签: wpf tooltip