在 App.xaml 中创建窗口时找不到资源定位器



我正在App.xaml.cs构造函数中创建我的主窗口,如下所示:

MainWindow wnd = new MainWindow();
Application.Current.MainWindow = wnd;
wnd.Show();

启动应用程序会给我一个XamlParseException,找不到名为"Locator"的资源。

这是可疑的线路:

<DockPanel x:Name="MainPanel"  DataContext="{Binding MainWindowViewModel, Source={StaticResource Locator}}" LastChildFill="True">

在App.xaml中使用StartupUri效果很好。

我做错了什么?!

我想你的Locator资源在App.xaml中。当你把代码放在构造函数中时,它不起作用的原因是App.xaml还没有加载。如果您看到visual studio生成的默认Main方法,您可以看到App.InitializeComponent是在构造函数之后调用的。xaml文件中的资源此时已初始化。

您可以通过将代码放入Application.Startup事件来解决此问题,该事件在调用Application对象的Run方法时发生。(如果设置了StartupUri,则在调用Run后也会对其进行初始化。)

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    var window = new MainWindow();
    window.Show();
}

当然,您可以订阅该事件并在事件处理程序中编写代码。但是,当我们想要订阅基类中的事件时,最好覆盖相应事件的OnXXX方法。

顺便说一句,你不需要这条线路Application.Current.MainWindow = wnd;。它将由wpf自动为您完成。

最新更新