meisenman
meisenman

Reputation: 1838

How to detect if the mouse is directly over an object type in WPF

I need to detect (true or false) if my mouse is over a specific type of object. There is one data template that the many objects use. I do not need anything from an instance of an object, I just need to detect if my mouse is above this type of element on the UI.

It would be something along the lines of:

If(mouse.DirectlyOver == StorageElementWrapper)
{
...
}

EDIT: my error is that I am using my type like a variable

Upvotes: 1

Views: 4067

Answers (3)

Csaba Toth
Csaba Toth

Reputation: 10729

A concept if you are interested in a particular item: create an OnMouseOver handler for that particular object (alternatively OnMouseEnter). Generally in WPF things work this event handling way rather than imperatively enumerating and discovering where is the mouse pointer. So this way the item itself can tell you if the mouse is over it. The item can have a public readonly property which exposes that, and your code can just get the value of that property.

Upvotes: 2

Tim S.
Tim S.

Reputation: 56576

It's important to note that DirectlyOver will very likely find something inside your element rather than the element you're actually looking for. To use this property, you'd want to look at the parent tree of the DirectlyOver element. Something along these lines, with FindAncestorOrSelf coming from this blog post:

if (Util.FindAncestorOrSelf<StorageElementWrapper>((DependencyObject)mouse.DirectlyOver) != null)
{
...
}

Or if you have code references to your StorageElementWrappers, (in this example, in a collection named myWrappers) and they derive from UIElement, this would probably be a better approach, using the IsMouseOver property:

if (myWrappers.Any(x => x.IsMouseOver))
    // do something

Upvotes: 3

meisenman
meisenman

Reputation: 1838

I was able to put the MouseEnter event in the border of my data template. This template is bound to my objects. Instead of trying to determine if the mouse was hovering over the object before performing an action, the

object_MouseEnter(object sender, MouseEventArgs e) 
{
     if(....)
     else
}

event fired each time an object was "entered into by the mouse" and I used conditional statements to decide how to handle the event.

Thanks for the previous suggestions regarding mouse events.

Upvotes: 2

Related Questions