System.TypeInitializationException when changing MainWindow startupUri WPF

1k Views Asked by At

I am trying to change the MainWindow location in a WPF application from the default startup URI: MainWindow.xaml to Views\MainWindow.xaml. where Views is a folder created inside the project folder.

Uri: this.StartupUri = new System.Uri(@"Views\MainWindow.xaml", System.UriKind.Relative);

I changed the uri and then the application breaks with the following error:

 An unhandled exception of type 'System.TypeInitializationException'occurred in PresentationFramework.dll


Additional information: The type initializer for 'System.Windows.Application' threw an exception.

I placed breakpoints and try-catch blocks in the Main method,the InitializeComponent method and the MainWindow constructor to no avail.It crashes and i can't catch the exception.

Main:

public static void Main() {
            try
            {
                wpfTest.App app = new wpfTest.App();
                app.InitializeComponent();
                app.Run();
            }catch(Exception ex)
            {
                Console.WriteLine(ex.InnerException.Message);
            }
        }

Does the startupUri have to be changed somewhere else too?It has only one reference :the one in the InitializeComponent method.

1

There are 1 best solutions below

1
On BEST ANSWER

To move the MainWindow to a Views folder (namespace), you have to follow this steps

  1. Change the class name in MainWindow.xaml

    <Window x:Class="WpfApp1.Views.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApp1"
            mc:Ignorable="d"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
    
        </Grid>
    </Window>
    
  2. Modify the namespace in MainWindow.xaml.cs

    namespace WpfApp1.Views
    {
        /// <summary>
        /// Interaktionslogik für MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
        }
    }
    
  3. Modify the App.xaml

    <Application x:Class="WpfApp1.App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:local="clr-namespace:WpfApp1"
                 StartupUri="Views/MainWindow.xaml">
        <Application.Resources>
    
        </Application.Resources>
    </Application>
    
  4. Move MainWindow.xaml to the Views folder

And thats it.

It does not matter which one you do first/last, but you have to do all of them.