2

I am trying to make a method where i can get the element that was clicked. In App.xaml.cs i have method OnPreviewMouseDown that is activated for each click in application.

Now i need some help with getting element name from sender (if this is even possible)

 static void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.RightButton == MouseButtonState.Pressed)
        {
            Control control = (Control)sender;   // Sender gives you which control is clicked.
            string name = control.Name.ToString();  //returns main window name, not element....

            string typee = sender.GetType().ToString();  //returns PPPMain.Views.MainWindow

        }
    }

I tried this and some other suggestions from internet but didn't find any solutions...

Thanks in advance!

Clemens
  • 123,504
  • 12
  • 155
  • 268
Pajkec
  • 67
  • 3
  • 12
  • 1
    `PreviewMouseDown` starts at the window and works its way down. `MouseDown` starts at the control and works it's way up. This is called "tunneling" and "bubbling", respectively. – Abion47 Nov 04 '16 at 09:51
  • 2
    Possible duplicate of [WPF Get Element(s) under mouse](http://stackoverflow.com/questions/45813/wpf-get-elements-under-mouse) – Pikoh Nov 04 '16 at 09:51

2 Answers2

3

Use the OriginalSource property of the MouseButtonEventArgs:

var element = e.OriginalSource as FrameworkElement;
var name = element?.Name;
Clemens
  • 123,504
  • 12
  • 155
  • 268
0

You could try using this code inside your event:

VisualTreeHelper.HitTest(this, e.GetPosition(this));

you can find more in this other topic: WPF Get Element(s) under mouse

Community
  • 1
  • 1
Lupu Silviu
  • 1,145
  • 11
  • 23