Search code examples
c#.netwpfwpf-controlspixelsense

How to determine on which UIElement a tagged object is placed?


In my app I use tagged objects. Now I'd like to react differently not only on the object that is placed on the surface, but also on the element it is placed on. Is this possible somehow? I couldn't find any information about it.


Solution

  • Yes, it is possible. Please show us your code so we can help you better.

    What you are looking for is probably Reflection.

    Did you know you can always check if an object is of a certain type with the is operator?

    var tag = myDependencyObject.Tag;
    if(myDependencyObject is CheckBox)
    {
        //...
    }
    else if(myDependencyObject is TextBox)
    {
        //...
    }
    

    To detect a change of the Tag-Property, listen to the DependencyPropertyChanged event like this:

    DependencyPropertyDescriptor prop = DependencyPropertyDescriptor.FromProperty(
        FrameworkElement.TagProperty,
        typeof(FrameworkElement));
    
    prop.AddValueChanged(aTaggedControl, this.YourEventHandlerMethod);