Search code examples
wpfunit-testingxamlbaml

Convert Baml file into usable XDocument for parsing


I want to be able to write unit tests against Xaml to look for improper patterns. We have issues where the Xaml is still valid and otherwise compiles and "works" fine but can cause hidden issues or lacks consistency. In order to help combat this we want to write unit tests against the files.

A simple example: If you define a grid and the grid column is bound to a numeric field on the underlying object then the column title of the grid should have the appropriate right align template per our internal standards. Leaving the template off the definition will yield a left aligned column header which doesn't really break anything other than our internal standards. Given this is basically xml, I should easily be able to write a test that interrogates the xml element, detects the existence of a numeric column and checks to make sure that the file also defines a title template that is right aligned. This way I don't have to rely on the developer or QA to cover things that are easily testable like this.

I have access to the assembly during the unit test process and can get to all the baml resource files by reading the manifest resource stream. But I can't figure out how to read them into a useful format that I could load into something like an XDocument for parsing and perusing. Has anyone done this? I've tried using Baml2006Reader, etc... without any good success.


Solution

  • If you want to convert BAML to XAML, you could take a look at the following BamlTranslator class on GitHub.

    It uses a BinaryReader to decompile the BAML.