Wednesday, June 22, 2011

WPF UserControl .cs file compilation error

I've met a very interesting WPF bug today, something that is hard to explain or reproduce, but might give terrible headaches if you don't know its source.

I had a WPF UserControl, with its xaml and cs files. Now, I know that in MVVM I shouldn't really use those much, but it was out of my control. The control had a section of resources (UserControl.Resources) in which there was a ResourceDictionary with some stuff in it. Considering that I'd removed all the merged dictionaries from this, I thought that I had no need of the dictionary tags, after all the Resources property of an element is already a ResourceDictionary. So it was something like this:

<UserControl ... >
<!-- <ResourceDictionary> with these tags commented the error occurs -->
... stuff ...
<!-- </ResourceDictionary> -->

The error itself is that, during compilation, the partial user control class defines in the code behind doesn't seem to find things from the xaml. Probably, the compiler fails building the xaml into a class, but fails silently, while the codebehind is completely disconnected from the xaml because it is the only partial file for that class name.

By selectively removing items in the resources I've narrowed it down to one of the converters. It was creating using the MarkupExtension trick, but it was also declared as a resource for some reason. I do not see why that should matter, but still.

Bottom line: when the partial codebehind class for a WPF user control (or maybe for windows as well) fails to connect to the xaml, it means it silently fails the compilation of the XAML and you should try checking the resources of the elements therein.