Determining the actual Runtime Type of an AssociatedObject

221 Views Asked by At

I have a behavior which I would like to attach to multiple controls and based on their type, I would like to write the logic and for this I need to determine the type of the associated object at runtime and I was wondering how can I do that

class CustomBehavior:Behavior<DependencyObject>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        if(AssociatedObject.GetType()==typeof(TextBox))
        {
            //Do Something
        }

        else if(AssociatedObject.GetType()==typeof(CheckBox))
        {
            //Do something else
        }
//....
//...
        else
            //Do nothing
    }
}

Will this work?

2

There are 2 best solutions below

0
On

I prefer:

if(typeof(TextBox).IsAssignableFrom(AssociatedObject.GetType()))
{
   ...etc
}

This will work for TextBox and any classes derived from it.

Side note: If you intend to use this behavior for controls (TextBox, ComboBox, etc), you'd better change it to Behavior<FrameworkElement>. This way you have access to all the common functionality of FrameworkElement (I.E L.I.F.E) without having to cast to a specific type.

0
On

You could use the is keyword, this will pickup the Type and derived Types

protected override void OnAttached()
{
    base.OnAttached();
    if(AssociatedObject is TextBox)
    {
        //Do Something
    }

    else if(AssociatedObject is CheckBox)
    {
        //Do something else
    }