Building Custom Controls in WPF

Here I will briefly introduce the types of custom controls one can build in WPF. Someone can ask why we need custom controls, if we can do everything with Styles and Control Templates?

Well, I would say still there are scenarios where one may need custom controls. One of them can be, while creating a reusable control that is composed of many other controls and so on, I want to create a control for data entry purposes, then that will use a Temporary address and Permanent Address. Here I don't want to copy/paste XAML code repeatedly for these two addresses. So, it's better to create a one User Control and reuse it. Another scenario can be, when we need a functionality that is not provided by existing WPF controls, a custom control can be the best solution for that.

UserControl vs Control

Now before proceeding further, it is important to have a look at the two most common classes of WPF, namely UserControl and Control.

UserControl should be chosen when you want to combine existing components, but here complex customizations won't be supported. So, if you need many customizations or you want control templates, then the Control class will be your choice. The best example can be themes, that require the Control class.

Now, let's quickly dig into the code. The first step here is to add one User Control to the application. Please don't get confused with the Windows Forms User Controls when adding because we want a User Control for our WPF application. So, select that:

User Control

Once your User Control is added, you will notice that the code behind file is inheriting a class UserControl as:
 
added User Control

Now to understand it in a better way, let's add one custom control as below:
 
add one custom control

After adding the control, you will see in the Solution Explorer that this time the XAML file is not added for the new custom control, but there is a new file under Themes as:

Solution explorer

On opening the CustomControlAddress.cs, you will notice that it is inherited from the Control class. Now before going forward, let's proceed to and first populate our ResidentialDetails control. For simplicity purposes, I am using only two fields named Address and City as:
 
Control

The code snippet above will provide you a simple address control, that is a good example of a User Control. Now let's proceed to and modify our Custom Control by modifying Generic.xaml as:

modify Custom control

Finally comes the testing part. In order to make these controls testable, we need to integrate them within our main XAML file as:
 
Testing

Once you are done with all these, you will get the desired output as:
 
Output

I hope you have an idea of how to use what. Enjoy learning!

Up Next
    Ebook Download
    View all
    Learn
    View all