I have a listbox that is databound to a Collection of objects. The listbox is configured to display an identifier property of each object. I would like to show a tooltip with information specific to the item within the listbox that is being hovered over rather than one tooltip for the listbox as a whole.
I am working within WinForms and thanks to some helpful blog posts put together a pretty nice solution, which I wanted to share.
I'd be interested in seeing if there's any other elegant solutions to this problem, or how this may be done in WPF.
Best Answer
There are two main sub-problems one must solve in order to solve this problem:
The first problem is rather simple to solve. By calling a method like the following within your handler for MouseHover, you can determine which item is being hovered over:
Then use the returned value to set the tool-tip as needed.
The second problem is that normally the MouseHover event isn't fired again until the cursor has left the client area of the control and then come back.
You can get around this by wrapping the
TrackMouseEvent
Win32API call.In the following code, the
ResetMouseHover
method wraps the API call to get the desired effect: reset the underlying timer that controls when the hover event is fired.With the wrapper in place, you can simply call
ResetMouseHover(listBox.Handle)
at the end of your MouseHover handler and the hover event will fire again even when the cursor stays within the control's bounds.I'm sure this approach, sticking all the code in the MouseHover handler must result in more MouseHover events firing than are really necessary, but it'll get the job done. Any improvements are more than welcome.