2010-08-06 70 views
0

做我的第一個MVVM WPF應用程序。我期望在App.xaml中看到Main()方法(我習慣Silverlight),但它不在那裏。我添加了我自己的Main方法。在Silverlight中,我創建了一個鏈接到ViewModel的View,並將其設置爲RootVisual。如何在WPF中正確打開我的第一個查看窗口?WPF/MVVM的主要方法有哪些?

回答

0

的方法有很多,但我認爲WPF相當於設置一個Silverlight RootVisual的是調用Application.Run

App.Run(new MainWindow()) 

一般情況下,沒有對或錯在這裏路也沒有一個公認的慣例。有些人在啓動事件中進行此調用。其他人不使用該事件並改寫OnStartup。還有一些人使用App.xaml中的StartupUri。

0

當我建立了我的第一個(也是迄今爲止唯一的)WPF項目,以顯示appliation的主窗口(稱爲MainWindow),我推翻了App類的OnStartup方法如下:

/// <summary> 
/// Raises the System.Windows.Application.Startup event. 
/// </summary> 
/// <param name="e">The <see cref="System.Windows.StartupEventArgs" /> that contains the event data.</param> 
protected override void OnStartup(StartupEventArgs e) 
{ 
    base.OnStartup(e); 

    // I did some app-specific stuff here... 

    MainWindow view = new MainWindow(); 

    // Allow all controls in the window to bind to the ViewModel by setting the 
    // DataContext, which propagates down the element tree. 
    MainWindowViewModel viewModel = new MainWindowViewModel(); 

    // and I did some more app-specific stuff here... 

    view.DataContext = viewModel; 
    view.Show(); 
} 

我相信這是MVVM應用程序的推薦方式(儘管如此);此代碼取自.NET 3.5應用程序。