0

I try to get the attribute values of an element, where the cursor is located like Tag, MouseLeftButtonDown or x:Name and so on. The Event is always raised, when F10 is pressed using CommandBindings:

XAML:

<Window.CommandBindings>
    <CommandBinding Command="Open" Executed="Executesd"/>
</Window.CommandBindings>
<Window.InputBindings>
    <KeyBinding Key="F10" Command="Open"/>
</Window.InputBindings>

Code:

private void Executesd(object sender, ExecutedRoutedEventArgs e)
{
    Point mo = Mouse.GetPosition(Window);
    var TagName = Mouse.DirectlyOver;
    MessageBox.Show("Mouselogic Open-Commands: " + mo.ToString() + " -> " + TagName);
}

With DirectlyOver I only can get the Control.Element. Thats not exactly what I am looking for.

<TextBlock MouseLeftButtonDown="MaximizeToolbar" Tag="FolderNameOrWhatever">Test</TextBlock>

I'm not using Windows.Forms. With Tag="FolderNameOrWhatever" I want to handle an action. I also need the parents Tag, when there is no Tag in the child located.

I ve found nothing with google that fits my problem, getting the elements attributsname an values where my cursor is located.

May someone can help? I'm new at C#. In JS I could solve it, but C# is very different.

  • Have you looked at `VisualTreeHelper`? That's what you would use to crawl up the visual tree to get the parent control. – Berin Loritsch Apr 26 '16 at 18:39
  • Thanks, yes I did. I thought there is another short way to do it. But I still don't know which command to use to get the cursors located element attribute. Thats my main problem. :( – Rowland Ownsya Apr 26 '16 at 19:12
  • How about http://stackoverflow.com/questions/45813/wpf-get-elements-under-mouse – Berin Loritsch Apr 26 '16 at 23:48
  • It's the same Result as with Mouse.DirectlyOver. I have read them all. :( The solution is to "convert" the Result it to a FrameworkElement. Took me many hours to find out how to solve. See answer below. Thanks for replying Berin and trying to help. :) – Rowland Ownsya Apr 27 '16 at 08:45

1 Answers1

0

Solved:

private void Executesd(object sender, ExecutedRoutedEventArgs e)
{
     Point mo = Mouse.GetPosition((UIElement)sender);

     FrameworkElement Happy = Mouse.DirectlyOver as FrameworkElement;
     MessageBox.Show("Mouselogic: " + mo.ToString() + " -> " + Happy.Tag);
}

Another way to do with VisualTreeHelper is like this (not full code):

.....
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(this); i++)
{
    Visual VisualChild = (Visual)VisualTreeHelper.GetChild(this, i);

    FrameworkElement Child = VisualChild as FrameworkElement;

    MessageBox.Show("Tag " + i + ": "+ Child.Tag +", Name: "+ Child.Name);
}
.....