Skip to main content

Building custom controls in WPF

Here I am going to briefly introduce with 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 reusable control which is composed of many other controls, i.e: I want to create a control for data entry purpose, which will take 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 which is not provided by existing WPF controls, here custom control can be the best solution.

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 lot of customizations or you want control templates, then Control class will be your choice. Best example can be themes, which requires Control class.

Now, let’s quickly dig into the code.
First step here is to add one User Control to the application. Please don't get confused with the Windows Form user control while adding because we want user control for our WPF application. So, select that:

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

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

After adding the control, if you will see Solution explorer, you will find that this time XAML file is not added for newly created custom control, but there is a new file under Themes as:

On opening the CustomControlAddress.cs, you will notice that it is inherited from Control class. Now before going forward, let’s go ahead and first populate our ResidentialDetails control. For simplicity purpose, I am taking here only two fields named Address and City as:

Above code snippet will give you a simple address control, which is best example of User control. Now let’s go ahead and modify our Custom control by modifying Generic.xaml as:

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

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

Hope you got an idea on how to use what. Enjoy learning !!!