VoodooChild
VoodooChild

Reputation: 9784

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?

Upvotes: 2

Views: 2861

Answers (2)

Heinz K
Heinz K

Reputation: 410

You only derive from DependencyObject , not from UIElement.

Upvotes: 2

AnthonyWJones
AnthonyWJones

Reputation: 189495

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.

Upvotes: 4

Related Questions