UIElement vs FrameworkElement in WPF/Silverlight

Greens picture Greens · May 10, 2011 · Viewed 16.9k times · Source

When do I derive from UIElement and FrameworkElement considering FrameworkElement inherits UIElement. Can anyone give real life examples?

Answer

markmuetz picture markmuetz · Sep 5, 2011

This is a good page for learning about WPF Architecture, and this answer only applies to WPF. Check out the UIElement and FrameworkElement sections, as well as the rest if you have time. Here's a quote from the linked page explaining why the 2 levels exist:

To this point in the topic, "core" features of WPF – features implemented in the PresentationCore assembly, have been the focus. When building WPF, a clean separation between foundational pieces (like the contract for layout with Measure and Arrange) and framework pieces (like the implementation of a specific layout like Grid) was the desired outcome. The goal was to provide an extensibility point low in the stack that would allow external developers to create their own frameworks if needed.

In short, UIElements know how to draw themselves (because they are derived from Visual). They can also use the routed events system by providing virtual methods like OnPreviewMouseDown and OnMouseDown, and part of the layout system by implementing Measure and Arrange.

FrameworkElements extend the layout system by implementing some of the virtual methods defined in UIElement. They provide a consistent way of setting layout properties, e.g. the Margin property and the MinWidth property. Additionally, the can be styled, and they can take part in data binding.

In answer to your question, if you need any of the extra abilities that FrameworkElement add, e.g. you need styles, binding or a layout system that's easier to use, then derive from them. Otherwise, derive from UIElement as there is a slight overhead from using FrameworkElement.

Also, you should have a look at the Control class (derived from FrameworkElement), as these provide useful new layers of functionality like Templating and properties like Padding.

Familiarising yourself with the inheritance hierarchy is also a good idea, you might want to derive from other classes in it (though probably no higher up the chain than Visual).