Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the name of the element on which I `clicked` / `mousedown`

Tags:

c#

wpf

xaml

I have a page whose root element is a Grid named Root.

I have many controls like TextBlock, TextBox, Grid, Rectangle, Border etc... who are children of Root.

Now, I want to have a MouseDown or PreviewMouseDown or Click on Root to find the name of the element on which I clicked.

So, how can I get the name of the element on which I clicked / mousedown ?

If I can get a solution that uses Tunneling, It will be much easier.

like image 997
Khushi Avatar asked Oct 15 '25 02:10

Khushi


1 Answers

RoutedEventArgs has property Source that Gets or sets a reference to the object that raised the event. Try this

xaml.cs

private void Grid_MouseDown_1(object sender, MouseButtonEventArgs e)
    {
        var mouseWasDownOn = e.Source as FrameworkElement;
        if (mouseWasDownOn != null)
        {
            string elementName = mouseWasDownOn.Name;
        }
    }

xaml

<Grid PreviewMouseDown="Grid_MouseDown_1">
    <StackPanel>
        <ComboBox ItemsSource="{Binding ItemsSource}"/>
        <Button Content="ok"/>
    </StackPanel>

</Grid>

Khushi sara project stackoverflow walon se he karana hai kya :)

like image 105
yo chauhan Avatar answered Oct 17 '25 16:10

yo chauhan