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

时间:2015-06-02 13:46:14

标签: c# wpf mvvm

我在一家已经采用MVC影响进入WPF \ MVVM范例的商店工作。在这个领域中,控制器首先被新建,这将新建它的视图和视图模型(通过MEF)。

我想知道如何进入app.xaml.cs来传递一个创建的窗口(以及它的依赖关系)而不是StartUpUri。我仍需要全球资源才能工作。

2 个答案:

答案 0 :(得分:2)

在app.xaml文件中添加Startup事件,如下所示:

<Application x:Class="Test.App" Startup="Application_Startup"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    <Application.Resources>

    </Application.Resources>
</Application>

然后,在app.xaml.cs文件中,处理事件并打开窗口:

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        Test.MainWindow window = new MainWindow();            
        window.Show();
    }

我不知道这是否会损害MVVM设计。

答案 1 :(得分:2)

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应用程序项目模板。)