4

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.

Khushi
  • 1,031
  • 4
  • 24
  • 48

1 Answers1

5

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 :)

yo chauhan
  • 12,079
  • 4
  • 39
  • 58
  • Nahi, sara project stackoverflow walo se nahi karwana. And by the way I am working on same problem from last 3 - 4 days. – Khushi Jan 05 '14 at 07:12
  • Thanks for answering my question once again. – Khushi Jan 05 '14 at 07:14
  • 1
    Being true this is not the way to solve that problem .I am sure what you trying to do is you will go through all elements except the one where MouseDown happen and will change there background to transparent. Suppose if there are many and many elements you will iterate them on every mousedown . and also dont forget to write e.Handled=true ; at the end otherwise it will keep down tunnelling and u will be iterating again and again – yo chauhan Jan 05 '14 at 07:17