Creating Custom WPF Derived Control with Attached XAML File – DEVELOPPARADISE
25/06/2018

Creating Custom WPF Derived Control with Attached XAML File

Introduction

I have created quite a few derived custom controls that include XAML. The problem is how to keep the control code and XAML together.

One approach is to use the Generic file, but this means that there the code is in one place and the XAML in a totally different place, and normally have a single Generic file in the solution. Also, you will get to have a very large XAML file unless you start to break it up. If you do not break up this file things can become very unmanageable very quickly.

You can also put the XAML in a ResourceDictionary such as app.XAML or a separate XAML file referred to in the app.XAML file, or in the Window or UserControl XAML files that use, but again this separates out the code and the XAML, and again should probably move the XAML for different controls into separate files. You can still associate the code and XAML by having them in the same folder, with similar names, but then this has to be referenced in with a MergeDictionaries in XAML. You also have to be careful with naming because if the code file and XAML file have the same name this confused Visual Studio and you get unintended results.

Solution

I came up with another way to do it. Basically, a UserControl is created and then change “UserControl” to the name of the control I want to derive from in both the XAML and code files. Then in the constructor for in the code file there is the following:

public StyledComboBoxControl() {     InitializeComponent();     var style = (Style)FindResource("Styling");     Style = style; } 

The finding the style resource has to be done after the InitializeComponent, it will not work before. The rest of the code behind contains whatever code is needed for the control to function correctly. In this case it is only DependencyProperty defintions for the all the extra properties this Control has beyond what is normally associateed with a ComboBox.

The XAML file consists of only the Resources section for the Control, which contains a ResourceDictionary which contains the Style with an associated Name attribute so that is can be found with the FindResource method.

Creating Custom WPF Derived Control with Attached XAML File

Creating Custom WPF Derived Control with Attached XAML File

Using the code

Using this control is just like using any control in WPF:

<local:StyledComboBoxControl Width="300"                              VerticalAlignment="Center"                              ItemsSource="{Binding Items}"                              Label="Sample Combobox"                              SelectedValue="{Binding SelectedValue2}"                              SelectedValuePath="Key" /> 

History

  • 2018-06-25: Initial Version