【问题标题】:System.TypeInitializationException when changing MainWindow startupUri WPF更改 MainWindow startupUri WPF 时出现 System.TypeInitializationException
【发布时间】:2017-09-18 07:26:36
【问题描述】:

我正在尝试将 WPF 应用程序中的 MainWindow 位置从默认启动 URI:MainWindow.xaml 更改为 Views\MainWindow .xaml. 其中Views 是在项目文件夹中创建的文件夹。

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

我更改了 uri,然后应用程序因以下错误而中断:

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


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

我在 Main 方法、InitializeComponent 方法和 MainWindow 构造函数中放置了断点和 try-catch 块,但无济于事。它崩溃了,我无法捕获异常。

主要:

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

startupUri 是否也必须在其他地方更改?它只有一个引用:InitializeComponent 方法中的那个。

【问题讨论】:

    标签: c# wpf uri mainwindow typeinitializeexception


    【解决方案1】:

    要将 MainWindow 移动到 Views 文件夹(命名空间),您必须按照以下步骤操作

    1. 更改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. 修改MainWindow.xaml.cs中的命名空间

      namespace WpfApp1.Views
      {
          /// <summary>
          /// Interaktionslogik für MainWindow.xaml
          /// </summary>
          public partial class MainWindow : Window
          {
              public MainWindow()
              {
                  InitializeComponent();
              }
          }
      }
      
    3. 修改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. MainWindow.xaml 移动到Views 文件夹

    就是这样。

    首先/最后做哪一个并不重要,但你必须完成所有这些。

    【讨论】:

    • 非常感谢先生!确实奏效了。我知道我在某处遗漏了一些东西,并且 app.cs 更改中的启动 uri 还不够。
    猜你喜欢
    • 2012-03-12
    • 2011-11-24
    • 2017-06-14
    • 2016-09-09
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    相关资源
    最近更新 更多