WPF trick: Debugging the XamlParseException

Update: See more information about XAML debugging here.

Here's a trick: When you work a lot with XAML, you'll be confronted to the dreaded XamlParseException sooner or later. This exception is thrown whenever something goes wrong while the XAML code is parsed. However, this exception is not very helpful. Typically, you get a message box telling you that:
An unhandled exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
Additional information: Cannot create instance of 'Window1' defined in assembly 'GalaSoftLb.Wpf.MyApplication, Version=1.0.2629.15160, Culture=neutral, PublicKeyToken=null'. Exception has been thrown by the target of an invocation. Error in markup file 'Window1.xaml' Line 1 Position 9.
Right... so what exactly went wrong? Well, it's easy to find out: In the code-behind, the XAML code is parsed in the method InitializeComponent which is automatically generated. This method is called in the Window object's constructor. So to have more details about the exception, put the call to InitializeComponent in a try/catch block. This way, you have access to the useless XamlParseException, but also to its InnerExceptions and to the StackTrace.
public partial class Window1 : System.Windows.Window { public Window1() { try { InitializeComponent(); } catch ( Exception ex ) { // Log error (including InnerExceptions!) // Handle exception } } }
Print | posted on Wednesday, March 14, 2007 8:49 AM

Feedback

# re: WPF trick: Debugging the XamlParseException

left by Daniel Puzey at 3/14/2007 11:33 AM Gravatar
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!

You'll find that the XamlParseException you catch is much more descriptive, and will give the correct position in the xaml file.

# re: WPF trick: Debugging the XamlParseException

left by Laurent at 3/14/2007 11:41 AM Gravatar
Very cool, thanks for the feedback, Daniel!

# re: WPF trick: Debugging the XamlParseException

left by Patrick Sears at 8/29/2007 3:58 PM Gravatar
I realize this is 5 months after your post -

Another way you can do this is when the IDE breaks into the debugger and shows you the dreaded "Cannot create instance of 'Window1' blah blah" exception, click View Detail, and drill down on the InnerException property until you get to the real exception.

That way, you don't have to add the XamlParseException to the caught exceptions, and you don't have to wrap InitializeComponent() in a try-catch.

This method is essentially the same as catching the XamlParseException (it's exactly the same exception, obviously), except without the extra work.

# re: WPF trick: Debugging the XamlParseException

left by Laurent at 8/30/2007 7:44 AM Gravatar
Hi Patrick,

Yeah you're a lucky guy, doing WPF with VS2008 :-) Back when I wrote this, VS2008 was not really that ready yet, and your solution doesn't apply to VS2005.

VS2008 makes programming and debugging easier, no doubts :-) Thanks for your comment.

Laurent

# re: WPF trick: Debugging the XamlParseException

left by Kurt at 9/19/2007 7:16 AM Gravatar
Actually, I get Patrick's solution on VS2005 v8.0.5. Laurent, can you not update fully and get it?

# re: WPF trick: Debugging the XamlParseException

left by Laurent at 9/20/2007 7:50 AM Gravatar
Hi Kurt,

One of my colleagues was also able to use the "VS2008-like" exception message box in VS2005. Unfortunately, he and I don't know why he gets it, and I don't. I also have VS2005 V8.05

Microsoft Visual Studio 2005, Version 8.0.50727.762 (SP.050727-7600)

What is the exact version number you use?

Greetings,
Laurent

# re: WPF trick: Debugging the XamlParseException

left by Rick at 9/28/2007 7:38 AM Gravatar
Tools->Options->Debugging->General->Check Enable Exception Assistant

# re: WPF trick: Debugging the XamlParseException

left by Laurent at 9/28/2007 7:55 AM Gravatar
Every day I learn new things... Rick, you're my new thing today :-) Thanks

# re: WPF trick: Debugging the XamlParseException

left by Narendra at 9/29/2007 1:27 AM Gravatar
Thanks for bailing me out of crunch situation. Actually i am developing an WPF application in crunch deadline situation..

Ur post helped to figure out problem in the code

# re: WPF trick: Debugging the XamlParseException

left by Bill at 10/20/2007 10:26 AM Gravatar
Hi,

I'm having this same problem - plus the generated method call to InitializeComponet() cannot be found with the error "Cannot resolve symbol InitializeComponent". Everything builds and when I create a new Windows project using the Extentions to VS2005 for WCF/WPF it runs just fine. Just can't resolve the InitializeComponent. I spent 12 hours today uninstalling everything from VS2005 to the runtimes for both .net 2.0 and 3.0 and still have the same problem. Anyone seen this or know what's up?

thanks!
Bill

# re: WPF trick: Debugging the XamlParseException

left by Dino at 3/27/2008 6:43 PM Gravatar
try...catch...That worked!
thanks!

# re: WPF trick: Debugging the XamlParseException

left by TBeaulieu at 4/8/2008 1:43 AM Gravatar
Thank you for this thread!

I spent all day trying to figure out why I couldn't catch the exception when trying to parse xaml with the reader.

At first, I couldn't even find the Debug...Exceptions menu item, so I thought there was a version difference. Eventually I figured out I just needed to customize the menu by adding it.

So... it's the only exception that by default can't be caught, and the only way to make it catchable is hidden! CRAZY!

# re: WPF trick: Debugging the XamlParseException

left by Martin Dahlborg at 6/11/2008 10:14 PM Gravatar
Great info thank you.

I tried the try-catch and found out that the XamlParseException was not thrown in InitializeComponent();

I needed to include my other methods also to find out that I had a mis-match in my App.Config (this is a WCF client).

try
{
InitializeComponent();
ClearScreen();
SetUpWcf();
}
catch...

I have now read the rest of the comments and can remove my try-catch ;)

# re: WPF trick: Debugging the XamlParseException

left by vera at 9/2/2008 3:17 AM Gravatar
thanks... your site realy help me.. =)

# re: WPF trick: Debugging the XamlParseException

left by Dim at 11/20/2008 2:58 PM Gravatar
hello,

I'm sure it's not the good place, but ...
I want to put a try catch for all my program.
in framework 2, I put it in the static void Main, but where can I put it on wpf ?

Thank you by advance

# re: WPF trick: Debugging the XamlParseException

left by Xigga at 11/20/2008 3:58 PM Gravatar
Thanks Patrick! I was getting the same error and the InnerException helped me find it. Now to fix that damn error. :(

# re: WPF trick: Debugging the XamlParseException

left by Laurent at 11/22/2008 5:37 PM Gravatar
Hey Dim,

In WPF, you put the “default error handling”, that is handling errors that are not caught anywhere else in the application, in the App.xaml. Use the event “DispatcherUnhandledException” for this. This event is called when an exception is not handled within the app, just before the application crashes.

Please note that you should not simply handle unhandled exceptions. It is preferable to use this event to log the error, clean up and then “crash gracefully”. If you simply handle unhandled exceptions, you leave the application in an unknown state which might cause even worse side effects later.

Cheers,
Laurent

# re: WPF trick: Debugging the XamlParseException

left by rüya tabiri at 11/25/2008 10:16 AM Gravatar
Thank you...

# re: WPF trick: Debugging the XamlParseException

left by Laurent at 12/12/2008 1:29 PM Gravatar
Hi,

This error comes because you changed the namespace in the class but not in the XAML file. Make sure that the x:Class attribute points to the correct class, including namespace, in the code behind..

Cheers,
Laurent

# re: WPF trick: Debugging the XamlParseException

left by Dan Lamping at 1/27/2009 6:02 PM Gravatar
I find that MarkupSource tracing is always the way to go:

http://www.wpfmentor.com/2009/01/how-to-find-out-what-that.html

# re: WPF trick: Debugging the XamlParseException

left by Artem Dmitriev at 3/2/2009 7:41 AM Gravatar
Thanls for your feedbakcs! Its cool..

# re: WPF trick: Debugging the XamlParseException

left by aliasy at 3/12/2009 8:58 PM Gravatar
Hi!

I had the same error. That is wired...
I had an mistake in method, that was called after InitializeComponent...

InitializeComponent();
loadData(); // bad - database data loading

I commented that method and everything now goes fine :)

# re: WPF trick: Debugging the XamlParseException

left by Sohbet Chat Sevgi Ask Arkadaşlık at 5/12/2009 12:41 AM Gravatar
Thank you...

# re: WPF trick: Debugging the XamlParseException

left by Norm Almond at 7/23/2009 2:29 AM Gravatar
Laurent
Cheers for the tip, wish I found it early as it would of saved a couple of hours of frustration.

# re: WPF trick: Debugging the XamlParseException

left by Zelalem at 7/25/2009 8:50 PM Gravatar
Thanks for your post. I tried these methods but still the exception exist. Then finally, i tried debugging it. All i did was have a breakpoint on InitializeComponents in code behind and then keep on pressing key F11 until it fails. And i finally got why it was failing. It was all because the xml parser i have (to parse some xml files - not the xaml itself) has some problems. To be exact, the path to those xml file was kept in app.config and was some reason system.configuration.configurationmanager.appsettings["keyNamehere"] was not returning the value. I know, the reference is added but something strange happened and it failed. So what i did is take all those constant values into settings.settings and finally everything works. Try this in case it helps/

Thanks all!
Zelalem

# re: WPF trick: Debugging the XamlParseException

left by Mike Hankey at 9/13/2009 4:23 PM Gravatar
Thanks for the tip...I was stugglin!

Mike

# re: WPF trick: Debugging the XamlParseException

left by subho100 at 11/18/2009 8:20 PM Gravatar
My app creates xml files which contains object description. When I load a saved file, it loads back the vector images perfectly with transform. I wanted to test by opening a xml file which was not created by my app. It gave me a XamlParseException but was not going to the catch. I have changed the catch from 'exception' to ' XamlParseException' but still it would not work. Any ideas?

# re: WPF trick: Debugging the XamlParseException

left by Laurent at 11/19/2009 2:12 AM Gravatar
Hi,

Without seeing some code, it will be hard to find what's wrong. I recommend you post your question, with more details, to StackOverflow (stackoverflow.com)

Happy coding
Laurent

# re: WPF trick: Debugging the XamlParseException

left by Luis at 12/17/2009 4:38 AM Gravatar
Quick Question...
In my MainWindow.xaml.cs file, I've got a try-catch block that is aimed at picking up any exception that may be encountered. Something like this:

try
{
InitializeComponent();
ReadAppConfigFile();
}
catch (Exception e)
{
System.Windows.MessageBox.Show (e.Message);
}

The problem is that the application, once the exception is caught, continues execution to a method like so (I'm using RibbonControl dll and my window is of type RibbonWindow):

private void RibbonCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
e.Handled = true;
}

After this code completes, I get the XamlParseException. My question is: How can I stop program execution as soon as the first exception is encountered? (That is, how can I stop the app from going to "CanExecute" method?) Any ideas?

# re: WPF trick: Debugging the XamlParseException

left by Nick at 6/5/2010 5:21 PM Gravatar
This helps.. thanks

# re: WPF trick: Debugging the XamlParseException

left by lost hours at 6/7/2010 1:55 PM Gravatar
Thanks for all the posts, it gave me a direction to look at.

i had similar problems to most 'System.Windows.Markup.XamlParseException', i looked at the inner exception error to try and discover the problem.

What worked for me, was making my security settings for my wpf application to "this is a full trust application".

hope this helps.

# re: WPF trick: Debugging the XamlParseException

left by Sowmya at 6/22/2010 9:29 AM Gravatar
It worked for me, with Security->Settings-> This is a full trust application, i have VS 2008 configured in my system.

# re: WPF trick: Debugging the XamlParseException

left by Daniel Werner at 3/28/2011 10:39 PM Gravatar
Hey, thanks for posting this. I found it useful.

# re: WPF trick: Debugging the XamlParseException

left by jatin at 6/3/2011 6:25 AM Gravatar
check this link very useful...

http://dotnetpeoples.blogspot.com/2011/06/xaml-parse-exception-was-unhandled-in.html

# re: WPF trick: Debugging the XamlParseException

left by Nanda at 7/1/2011 9:57 AM Gravatar
Thank you very much this is a really useful post...to the point and sensible

# re: WPF trick: Debugging the XamlParseException

left by Mani at 11/29/2011 12:23 AM Gravatar
Thanks a lot . that really helps

# re: WPF trick: Debugging the XamlParseException

left by ajay at 12/3/2011 10:05 AM Gravatar
Solution for the Exception:Xaml parse exception is to
enclose the code that raises exception within try ..catch....it really works............i fought for 2days its a simple error .........

# re: WPF trick: Debugging the XamlParseException

left by mandork at 1/17/2012 2:56 PM Gravatar
Thanks it worked

# re: WPF trick: Debugging the XamlParseException

left by johanna at 4/5/2012 1:29 PM Gravatar
Hello,

I did try but nothing works, can you help me please ?

Thanks

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;
using SPSClient = Microsoft.SharePoint.Client;
using System.Collections.ObjectModel;

namespace TipsList
{
/// <summary>
/// Interaction logic for Page1.xaml
/// </summary>
public partial class Page1 : Page
{
string siteUrl;
SPSClient.ClientContext clientContext;
SPSClient.Web clientWeb;
public Page1()
{
try
{
InitializeComponent();

//The Url
siteUrl = "http://site/SandBox";
//The Site Context using ClientContext class
//This will create a Client connection to Web Application
clientContext = new SPSClient.ClientContext(siteUrl);

//The Web Site to Open

clientWeb = clientContext.Web;

var salesInfoList = clientContext.Web.Lists.GetByTitle("Tips");

//Define the CAMLQuery this will be used to Query to the List

SPSClient.CamlQuery Query = new SPSClient.CamlQuery();

SPSClient.ListItemCollection listData = salesInfoList.GetItems(Query);

//Now Execute the Query

var queryResultSaleListItems = clientContext.LoadQuery(listData);

clientContext.ExecuteQuery();

//Read the Data into the Object

var SalesList = from Sales in queryResultSaleListItems
select Sales;
ObservableCollection<Tips> colSales = new ObservableCollection<Tips>();
//Read Every List Item and Display Data into the DataGrid
foreach (SPSClient.ListItem item in SalesList)
{

var tips = new Tips();
tips.StateTitle = item.FieldValues.Values.ElementAt(2).ToString();
tips.ProductName = item.FieldValues.Values.ElementAt(4).ToString();
tips.Quantity = item.FieldValues.Values.ElementAt(5).ToString();

colSales.Add(tips);
}
}
catch (Exception ex)
{
// Log error (including InnerExceptions!)
// Handle exception
}

}


}
}

# re: WPF trick: Debugging the XamlParseException

left by johanna at 4/5/2012 1:32 PM Gravatar
sorry changing > my security settings for my wpf application to "this is a full trust application".

Helped me actually
thanks a lot

# re: WPF trick: Debugging the XamlParseException

left by Allen Marshall at 4/17/2012 6:49 AM Gravatar
If I trap the exception in the MainWindow.xaml.cs and I can see the exception that caused the problem, is there anyway to stop processing the window and close the app gracefully right away? Seems like the XamlParseException stomps on the real exception so when it bubbles up to my unhandled exception handlers the source information is no longer there and the misleading XamlParseException message is displayed which means nothing to the user.

1) Some Exception raised deep in the guts, caught and rethrown up the hierarchy
2) This causes the ViewModelLocator to not be instantiated
3) MainWindow happily starts up but cannot locate the Locator resource... so it raises a XamlParseException

What I want is for step 3 to never happen and just go to the outermost unhandled exception handler which displays the problem nicely.

Thanks for any insight.

# re: WPF trick: Debugging the XamlParseException

left by Allen Marshall at 4/18/2012 1:12 AM Gravatar
<ResourceDictionary>
<!-- MVVM Related -->
<!-- View Model Locator-->
<ViewModel:ViewModelLocator x:Key="Locator" d:IsDataSource="True"/>

So the problem with the XamlParseException occurs when this resource is created. Is there an alternative way to do this that will play nice with Blend and so on? Code-behuind?

# re: WPF trick: Debugging the XamlParseException

left by Razvan at 5/16/2012 11:25 PM Gravatar
Awesome tips both in article and in 2 comments:
left by Daniel Puzey
and
left by Rick.

Thanks guys!
Sharing is caring!

# re: WPF trick: Debugging the XamlParseException

left by Maria Im at 11/7/2012 12:58 AM Gravatar
Thanks Daniel Puzzey for your comment. That wraps up my lousy day at work :)
Comments have been closed on this topic.