Tuesday, November 08, 2016

Defining DEBUG only content in XAML

For a number of applications I've worked on, I've had content in the UI that should only be included in specific builds. Usually, I do this for the debug build but I've also done this for specific test builds too.
I've added text to make it clear that it's a specific build and I've also used this for accessing test specific content such as secret menus for impacting connectivity or for enabling test datasets.
Previously I've done this by adding named controls in the UI and then using the code-behind on the page to hide or show the content as appropriate. It's not been ideal but it's worked.
I've wanted something that was XAML only but never come up with anything appropriate. I'd looked at adding scripts at build time to control what was included based on properties or extensions in the markup but that wasn't great either.
In looking at how Xamarin.Forms works I came up with another idea.

It lets me have an app that looks like this in release mode
and like this in debug

Amazingly it's all configured in XAML
and changing the build config in VS causes the designer preview to update too.

And it only took a tiny amount of code.
enjoy.

***UPDATE***
But what about performance?

I don't think I use this enough to be concerned about the cost of having a simple extra control in the visual tree, but it's worth a little thought.
It turns out there's a simple way to achieve the same result with less code and without leaving invisible controls on the tree.
It's still not a perfect solution as this still leaves an empty content presenter lying around and does mean a line of code is executed in release builds but I think this is the best that's possible with a single code file.

0 comments:

Post a Comment