WPF Trick: How Can We Debug The XamlParseException

Posted by nicolewells.n on 06-Oct-2017 02:34

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
    }
  }
}

All Replies

This thread is closed