WPF命令行和带有designdata的MvvmLight

时间:2013-02-13 06:33:47

标签: c# .net mvvm command-line mvvm-light

我想覆盖OnStartup,就像在这个帖子中解释的那样

WPF Command Line

现在问题是我正在使用MVVM Light Toolkit抛出一个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 Light Toolkit结合使用?

更新13.02.2013 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();
}

1 个答案:

答案 0 :(得分: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();