Debugging the XamlParseException
In a
previous post, I mentioned how you can get more details about the XamlParseException thrown when something is wrong with the XAML (but you don't know what exactly). Well, a reader named
Daniel Puzey made a comment to that, and I think it's worth posting that again:
There's another trick to this. Often, by default, you'll get an error reported at Line 1 of the xaml, which is an obvious lie. You can catch the original exception, though:
- Open the "Exceptions" window (Debug/Exceptions) in Visual Studio.
- Click "add"
- Add "System.Windows.Markup.XamlParseException"
- Check the box to break on throw for this exception.
- Hit F5!
- Click "add"
- Add "System.Windows.Markup.XamlParseException"
- Check the box to break on throw for this exception.
- Hit F5!
You'll find that the XamlParseException you catch is much more descriptive, and will give the correct position in the xaml file.
How to find binding errors?
Another annoying thing when the XAML is wrong is that binding errors get swallowed silently. You don't know what's wrong, but the binding doesn't work as expected. There is a little-known way to find out more about what went wrong. For example, the following code doesn't work, but no error is shown (well, in that case it's easy to find out: The ElementName refers to mainWindow2, which doesn't exist (should be mainWindow).
<
Window
x:Class
="WindowsApplication2.Window1"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
Title
="WindowsApplication2"
Height
="300"
Width
="300"
x:Name
="mainWindow"
>
<
TextBlock
Text
="{Binding ElementName=mainWindow2, Path=Title}"
/>
</
Window
>
To find out what's wrong, do the following:
- Execute your application in debug mode (by pressing F5) in Visual Studio
- Check the window "Output" (if missing, this window is displayed by choosing the menu "Debug / Windows / Output"
- Make sure that the "Show output from" combo is set to "Debug".
- The binding error can be found, usually on the last line:
![Binding error in output window (debug mode) Binding error in output window (debug mode)](http://www.galasoft-lb.ch/blogs-all/2007040201.gif)