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?
I prefer:
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 ofFrameworkElement
(I.E L.I.F.E) without having to cast to a specific type.