Skip to main content
 首页 » 编程设计

c#之在 WPF 中启动应用程序,如何不使用启动 uri,而是使用窗口实例

2024年02月06日15kerrycode

我在一家将 MVC 影响纳入 WPF\MVVM 范例的商店工作。在这个领域,首先更新 Controller ,然后更新它的 View 和 View 模型(通过 MEF)。

我想知道如何进入 app.xaml.cs 以将创建的窗口(及其依赖项)而不是 StartUpUri 交给它。我仍然需要全局资源来工作。

请您参考如下方法:

WPF 应用程序的默认项目模板假定您希望主应用程序类基于 xaml。但是,这不是必需的,您可以更改它。这样做允许您编写自己的应用程序入口点方法,并创建您自己的应用程序实例,并按照您想要的方式进行配置。

因此,您可以删除 App.xaml 和 App.xaml.cs 文件并在其位置创建一个 App.cs 文件。在该文件中,执行如下操作:

internal class App : Application 
{ 
    [STAThread] 
    public static int Main(string[] args) 
    { 
        App app = new App(); 
        // Setup your application as you want before running it 
        return app.Run(new MainWindow()); 
    } 
 
    public App() 
    { 
        // (Optional) Load your application resources file (which has a "Page" build action, not "ApplicationDefinition", 
        // and a root node of type "ResourceDictionary", not "Application") 
        Resources = (ResourceDictionary)Application.LoadComponent(new Uri("/MyAssemblyName;component/Resources.xaml", UriKind.Relative)); 
    } 
} 

这允许您在运行应用程序之前以任何您想要的方式指定您的主窗口。您的应用程序资源文件看起来像这样:

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <!-- Put application resources here --> 
</ResourceDictionary> 

我总是以这种方式构建我的 WPF 应用程序,因为它看起来更简单并且可以更好地控制应用程序的运行方式。 (我在 Visual Studio 中创建了自定义 WPF 应用程序项目模板。)