Pajkec Pajkec - 1 month ago 16
C# Question

get name of element under mouse cursor on mouse click

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!

Answer

Use the OriginalSource property of the MouseButtonEventArgs:

var element = e.OriginalSource as FrameworkElement;
var name = element?.Name;
Comments