Sunday, July 31, 2011

Difference between a UserControl and a CustomControl

Tweet

If you are thinking to build a control and apply the same to more than one place, you can take two kinds of approaches. Either you can create an User control inheriting from UserControl and adding a XAML for your control or use CustomControl to write yourself. Either one of them you choose they have their own pros and cons. Here in this post I will define what are the differences between the two approaches so that you can choose either one of them based on your requirement.

Before we start lets define both the terms:

UserControl : A usercontrolis a reusable chunk of user interface that is built up as a composition of other UIElement in the same style the main UI is built. In other words, a user control is just like a normal application block that can be used as Reusable component, and can be defined both using XAML and code together. It gives you a fresh UI canvas where you can define your custom reusable component that can be used widely in the application. In WPF, UserControl acts as a base class for any reusable component, but if you are looking for inheriting some other base, you can look into this.

Limitation of UserControl :

1. Appearance of an UserControl cannot be changed using a Template. Even though it has a property for Template, but it is of no use, as you cannot change the appearance of UserControl through this property.

2. UserControl is derived from ContentControl, thus if you change the Content of an usercontrol the entire UI will be replaced with that content.

3. As UserControl has both XAML and code behind. But as XAML can be used only once for entire inheritance hierarchy, you cannot use XAML for any class that inherits from your userControl. This is actually because Application.LoadComponent loads up the XAML once and is incompatible with inheritance. Thus when loading the XAML, the IComponentConnector interface is used to hook events and fields from XAML, hence you cannot replace XAML from your base class.

Custom Control: A customcontrol is a User interface element that has a distinct behaviour. A CustomControl is just a class that has one default appearance defined in Generic.xaml style which can be replaced by Template and Style at runtime but the behaviour you define for the control remains the same. So choose a CustomControl only when you need a certain kind of behaviour which is not there with the existing controls you have.


Read more: Daily .Net Tips
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://dailydotnettips.com/2011/07/27/difference-between-a-usercontrol-and-a-customcontrol/

Posted via email from Jasper-Net