Siyamak Shahpasand
Siyamak Shahpasand

Reputation: 303

How to detect a Custom Control under mouse cursor while the mouse is down in C#-WPF?

I use RadioButton to Create Custom Control and want to know How do I detect it when mouse move over it while its left button is pressed and held down? Of course I know it is possible with VisualTreeHelper but this method returns only top most element (not my own custom control).

Upvotes: 0

Views: 551

Answers (1)

Natxo
Natxo

Reputation: 2947

You can use a snippet like this to dig deeper in the VisualTree, and return the first control of the specified type it finds:

public static T GetVisualChild<T>(Visual parent) where T : Visual
{
    T child = default(T);
    int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < numVisuals; i++)
    {
        Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = v as T;
        if (child == null)
        {
            child = GetVisualChild<T>(v);
        }
        if (child != null)
        {
            break;
        }
    }
    return child;
}

To find a MyCustomControl inside the someVisual control:

MyCustomControl myControl = GetVisualChild<MyCustomControl>(someVisual);

Upvotes: 2

Related Questions