Tuesday, December 23, 2008

XAML Syntax Discovery

I know I've been promising to finish some LINQ provider stuff, but I have ADD...

If you're like me, you have had a bit of trouble debugging data binding in XAML. Typical syntax looks like this:

<TextBlock Text="{Binding ElementName=mySourceElement,Path=Text}">

... which, to me, looks like some kind of crazy nutjob specialized syntax specific to binding that has no real (Intelli)sense. For example, where can you use "{Binding...}"? What classes can you use this with?

Turns out I should read a syntax guide. The code block above is essentially equivalent to:

<TextBlock>
<TextBlock.Text>
<Binding Path="Text" ElementName="mySourceElement">
</TextBlock.Text>
</TextBlock>

I didn't understand that the above syntax was a fairly simple, standardized shortcut because I have never (until just now) seen an example of data binding that used the long form. Perhaps I should have done more to try to understand the underlying syntax of XAML, but this sample really opened my eyes and helped me diagnose problems. In particular, by avoiding the braces shortcut in the top syntax, you get much more effective Intellisense which has helped me a lot with my WPF data binding.

I could have known this had I done more boring reading. The full details are available in the MSDN library page called XAML Syntax Terminology. In particular, the Markup Extensions section explains why some classes, such as StaticResource and Binding, can use this syntax. For more information on how markup extensions work, check out Markup Extensions and XAML on MSDN.

No comments: