Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIElement vs FrameworkElement in WPF/Silverlight

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

like image 928
Greens Avatar asked May 10 '11 21:05

Greens


1 Answers

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).

like image 114
markmuetz Avatar answered Sep 18 '22 22:09

markmuetz