Implementing Mouse Hover in WPF

We’ve spent the past couple of weeks at work giving ourselves a crash course in Windows Presentation Foundation (WPF) and LINQ.  I’m working on a code example that will switch the datatemplate in a list item when the mouse hovers over it.  Unfortunately, WPF has no MouseHover event like Windows Forms does.  The usual googling didn’t cough up a ready-made answer.  Some hacking on one example did reveal a half-answer (not ideal, but at least a start).

First, I set the ToolTip property of the element I used to organize my data (in this case, a StackPanel).  Next, I added a ToolTipOpening event for the StackPanel.  Here’s the code for StackPanel_ToolTipOpening:

private void StackPanel_ToolTipOpening(object sender, ToolTipEventArgs e)
{
e.Handled = true;
ContentPresenter presenter = (ContentPresenter)(((Border)((StackPanel)e.Source).Parent).TemplatedParent);
presenter.ContentTemplate = this.FindResource("Template2") as DataTemplate;
}

The result: instead of a tooltip displaying when you hover over a listbox row, the standard datatemplate is replaced with an expanded one that displays more information.  This approach definitely has flaws.  Beyond being a hack, there’s no way to set how long you can hover before the templates switch.

Switching from an expanded datatemplate back to a standard one involved a bit less work.  I added a MouseLeave event to the expanded template.  Here’s the code for the event:

private void StackPanel_MouseLeave(object sender, MouseEventArgs e)
{
ContentPresenter presenter = (ContentPresenter)(((Border)((StackPanel)e.Source).Parent).TemplatedParent);
presenter.ContentTemplate = this.FindResource("ScriptLine") as DataTemplate;
}

So once the mouse moves out of the listbox item with the expanded template, it switches back to the standard template.  Not an ideal solution, but it works.

This link started me down the path to finding a solution (for reference).

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.