Adding code-behind to XAML ResourceDictionary files in WPF

As any WPF developer knows, XAML can get messy very quickly with all the nested elements and tabulation. However, at least one type of nested elements, the resources, can be easily tidied up by moving them to external ResourceDictionary files. You can then include them by either specifying a dictionary Source property or by using MergedDictionaries.

For example, in one of my projects I had to make an editor for a property that could take values of specific but different types (depending on how it was set up). In the view, I was using a ContentPresenter to display different controls for different types using multiple data templates stored in resources (as seen here): a text box for text, another text box with buttons for number, a toggle button for boolean, etc. Initially I only had a couple of types to worry about, but, as the project grew, I’ve added a lot more. Separating the data templates and moving them to a resource dictionary originally posed a problem – there were a lot of event handlers in the code-behind, like handlers for +/- buttons, handler for the “locate file” button, handler for text input to prevent non-numeric characters in a text box intended for numbers, etc.

As it turned out, the ResourceDictionary, just like everything else, can actually have its own code-behind class, where it’s possible to define event handlers and whatever else you may need.

To add a code-behind class, you just need to add any partial class to the project and link it with the XAML file. Ideally, the code-behind file should be in the same namespace as the dictionary and have the same file name, but with “.cs” (or “.vb”) appended to it, for example MyResourceDictionary.xaml.cs.

To link the XAML definition to the code-behind, use the x:Class attribute, just like so:

The value in x:Class should be equal to the fully-qualified name of the code-behind class that you’ve just created. Once you set it up, Visual Studio will be able to set up event handlers directly in your code-behind, much like it does for Windows, Pages, etc.

Using this trick I decoupled a large portion of my view code into external files, without sacrificing anything.