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
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 confuses Visual Studio and you get unintended results.
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 both the XAML and code files. Then in the constructor in the code file, there is the following:
var style = (Style)FindResource("Styling");
Style = style;
Then 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 definitions for all the extra properties this
Control has beyond what is normally associated with a
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
Using the Code
Using this control is just like using any control in WPF:
- 2018-06-25: Initial version
Has been working as a C# developer on contract for the last several years, including 3 years at Microsoft. Previously worked with Visual Basic and Microsoft Access VBA, and have developed code for Word, Excel and Outlook. Started working with WPF in 2007 when part of the Microsoft WPF team. For the last eight years has been working primarily as a senior WPF/C# and Silverlight/C# developer. Currently working as WPF developer with BioNano Genomics in San Diego, CA redesigning their UI for their camera system. he can be reached at firstname.lastname@example.org.