Referring to Enums (and Other Nested Types) in XAML
This is going to be a brief post, because it’s really just about making the XAML parser happy in an obscure case.
I ran into a problem when I tried to refer to an enum in XAML. This isn’t something you need to do often, but sometimes you need the full, qualified name. Suppose I have a class like this:
public class SuperMario2
{
public enum Characters
{
Mario,
Luigi,
Toad,
Princess
}
}
Now suppose I have a need to refer to these in XAML. I might try something like this:
{x:Static local:SuperMario2.Characters.Mario}
But the compiler complains:
I couldn’t figure out why this wouldn’t work, until I realized that the problem isn’t specific to enums. The problem is that nested types aren’t supported in XAML, and this is just one instance of that. Fortunately, I found this post on MSDN that reveals an undocumented trick to make this work. (Scroll about 3/4 of the way down.) It turns out that what you actually want to do is this:
{x:Static local:SuperMario2+Characters.Mario}
And the compiler is happy.
Hope this helps.