augre
augre

Reputation: 340

How to open WPF application from an other WPF both using MVVM?

I am trying to us the demo code from wpf chrometabs and in the other application I just added a button that calls the constructor of the demo:

private void FrontendDebug_Click(object sender, RoutedEventArgs e)
{
   Demo.MainWindow mainWindow = new Demo.MainWindow();
   mainWindow.Show();
}

The problem is that it throws an exception at the InitalizeComponent:

Exception

I read somewhere that in MVVM, the DataContext should be set before calling InitializeComponent() but I don't know if that is the problem here or how to do it if it is.

Upvotes: 0

Views: 581

Answers (1)

thatguy
thatguy

Reputation: 22079

The error that you get points out, that you use a StaticResource markup extension to reference a resource with key Locator that is not found in this line:

DataContext="{Binding Source={StaticResource Locator},Path=ViewModelMainWindow}"

The locator is defined in the application resources, so it is accessible in the whole application. Either you accidentially removed it or there is a typo in App.xaml. Make sure that it looks like this.

<Application x:Class="Demo.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" d1p1:Ignorable="d" xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006">
    <Application.Resources>
        <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" xmlns:vm="clr-namespace:Demo.ViewModel" />
    </Application.Resources>
</Application>

I am trying to us the demo code from wpf chrometabs and in the other application I just added a button that calls the constructor of the demo:

If you have another application that uses the demo project as library, the call below will only create an instance of the MainWindow. It will not bootstrap the application in the demo project.

Demo.MainWindow mainWindow = new Demo.MainWindow();

Consequently, the App object from the demo project is never created and its resources are not available. Even if it would be bootstrapped, the resources defined in App.xaml only apply to this application, nothing else.

Therefore, the mainWindow instance will try to find the resource in your application, not in the demo application. Since it is not defined there, you will get an exception. You could add the view model locator to your application's App.xaml resources, but keep in mind that is applies to all resources defined on the application level.

Upvotes: 1

Related Questions