Search code examples
c#silverlightsilverlight-4.0dependencyobjectuielement

Casting error for UIElement on runtime


I get runtime error when I do this.

I have this class:

public abstract class AnnObject : DependencyObject

and when I do this it compiles fine, but throws a runtime error...

AnnObject aa;
var b = (DependencyObject)aa;
var c = (UIElement)b;

The error I get is cannot cast AnnObject to UIElement.

Can someone please briefly explain this behaviour?


Solution

  • The class hiearchy in Silverlight for UI components is:-

    DependencyObject
      UIElement
        FrameworkElement
          Control
    

    So as Heinz points out you would need to have derived from UIElement order to be able to cast to UIElement and DependencyObject. Personnally I can't see deriving from DependencyObject being that useful. I would normally start at FrameworkElement, Control or even higher.