2013-02-13 69 views
0

我想覆蓋OnStartup就像是在這個線程WPF命令行和MvvmLight與designdata

WPF Command Line

解釋現在是我使用的MVVM光工具包,它拋出一個XamlParseException問題,它說,「定位」不知道,了這一點:

DataContext="{Binding Main, Source={StaticResource Locator}} 

我沒有問題,設計時間

的App.xaml

<Application.Resources> 
    <!--Global View Model Locator--> 
    <vm:ViewModelLocator x:Key="Locator" 
         d:IsDataSource="True" /> 
</Application.Resources> 

我重寫

protected override void OnStartup(StartupEventArgs e) 
{ 
    base.OnStartup(e); 

    if (e.Args.Length > 0 && e.Args[0] == "\\start") 
    { 
     /* do stuff without a GUI */ 
     MessageBox.Show("Start"); 
    } 
    else 
    { 
     MainWindow mainWindow = new MainWindow(); // <-- Exception 
     ViewModelLocator locator = new ViewModelLocator(); 

     mainWindow.DataContext = locator.Main; 
     mainWindow.ShowDialog(); 
    } 
    this.Shutdown(); 
} 

如何使用命令行結合的MVVM光工具包?

更新2013年2月13日10:10

有了這個覆蓋不再有例外。但是,爲什麼我必須將ViewModelLocator添加到資源,如果它已在xaml中聲明?

protected override void OnStartup(StartupEventArgs e) 
{ 
    base.OnStartup(e); 

    if (e.Args.Length > 0 && e.Args[0] == "\\start") 
    { 
     /* do stuff without a GUI */ 
     MessageBox.Show("Start"); 
    } 
    else 
    { 
     ViewModelLocator locator = new ViewModelLocator(); 
     Resources.Add("Locator", locator); 
     MainWindow mainWindow = new MainWindow(); 

     //DataContext="{Binding Main, Source={StaticResource Locator}}" 
     //mainWindow.DataContext = locator.Main; 

     mainWindow.ShowDialog(); 
    } 
    this.Shutdown(); 
} 

回答

0

你要檢查,如果資源已經包含了定位

ViewModelLocator locator; 
if (!Resources.Contains("Locator")) 
{ 
    locator = new ViewModelLocator(); 
    Resources.Add("Locator", locator); 
} 
else 
{ 
    locator = (ViewModelLocator) Resources["Locator"]; 
} 

WorkingWindow mainWindow = new WorkingWindow(); 
mainWindow.ShowDialog();