简体   繁体   中英

WPF Command Line and MvvmLight with designdata

I want to override the OnStartup like it is explained in this thread

WPF Command Line

Now is the problem that I'm using the MVVM Light Toolkit which throws a XamlParseException ,which says that the "Locator" isn't known, on this point:

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

I have no problem to design time

App.xaml

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

My override

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

How can I use command line in combination with the MVVM Light Toolkit?

Update 13.02.2013 10:10

With this Override there is no longer an exception. But why I have to add the ViewModelLocator to the resources if it is already declared in the 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();
}

you have to check if the resource contains already the locator

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM