I'm trying to implement a tool-tip system in a WPF MVVM application. The tool-tip is supposed to appear in a certain Label that is a part of the MainWindow (not hovering at the mouse pointer) and should happen on mouse-over (ideally with a configurable delay, but that is unimportant), calling a method in the appropriate ViewModel. The ViewModel will then deal with contacting the Model layer that will resolve which tool-tip to display etc.
My problem is how to get a mouse-over event from the view to the ViewModel, along with the identity of the object that fired the event (so I can resolve the right tool-tip for it). Let's say I have a <Label Name="MyLabel" Content="This is a label" />
in my SettingsView.xaml, how do I get it to call the GetTooltip(string id)
method in SettingsViewModel with MyLabel as the argument (or otherwise accessible) on mouse-over? Can I use a regular <Trigger>
to do it somehow?
What you need to do is hook up some commands (the preferred approach for ViewModels to interact with events in the View) to the Mouse events and then "populate" your "tooltip" control with the appropriate information.
For example, your ViewModel has a ToolTip property (that represents a one-way, get only ToolTipViewModel) that can be bound to an area of your UI (with a DataTemplate). You bind up to the new "MouseOver" command and populate/nullify the object that is in your ToolTipViewModel property based on the commands. This allows for testability, zero-code behind, and using DataTemplates to build your tooltip presentation.
Check out this link to see if building Commands and binding to them on normally "Uncommanded" controls might solve your problem.
First, have you tried the built-in ToolTip
control? It might give you what you need for free, and it can be styled/templated to host complex content.
Second, you may be able to use the MouseEnter
event available on every WPF control. You'd have to attach your handler to the controls you want to support, though.
In order to generically cover every control, consider attaching a handler to the parent Window
's PreviewMouseMove
event (or override OnPreviewMouseMove
in the Window's code-behind), which will be called whenever any child element is about to receive one. You can then find out what control is under the mouse pointer by using HitTest
. This isn't terribly efficient, though, which is why you may be better-off with the built-in ToolTip
control.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With