Jerry Nixon @Work: Walkthrough: A Custom Control in XAML isn’t a User Control

Jerry Nixon on Windows

Tuesday, January 8, 2013

Walkthrough: A Custom Control in XAML isn’t a User Control

imageCatnip to developers is truly reuse. Redundant code is a source of continual agony to architects and maintenance developers alike. In XAML we have a few ways to reuse our code that aren’t just C# strategies like inheritance and static methods.

XAML Reuse Strategies

1. Higher Resources

The <Resources /> property of a page or control is within the scope of any child element. As a result, this raises the scope of styles, templates, and variables to more than one UI element. The Page resources property is the highest scope available in a single UI.

2. Resource Dictionaries

A resource dictionary is a file. It contains anything you can put in the <Resources /> property of a page or control. Since it is an external file, the contained styles, templates, and variables can be shared by unrelated controls or pages across the project.

3. User Controls

A user control is a layout container or group of controls that act (in a way) like a little bitty page. You can use and reuse a user control on the same page or across multiple pages in a project. A user control has code-behind and an event pipeline much like a Page does.

4. Custom Controls

A custom control is lightweight. It is sub-classing an existing control. For example (and in this demo) you can sub-class the Button. Sub-classing lets you inherit the functionality of the base and inject your custom behaviors into it. The resulting control remains a button. Developers interact with it like a standard button.

Creating a custom control

In the video above I build out a simple custom control sample. The code (or nearly the code) for the sample can be seen in my StackOverflow answer found here. Since I wrote the sample for the answer, I figured I would put together this blog article. I hope it was useful.

Best of luck