Unable to show WPF application when manually configuring MainWindow and composing application (MEF)

I received my hands from MEF for a week, and I am trying to create a WPF application that loads imported controls from MEF.

I created a WPF application project and removed the default window and the launch URI of the application. Then I processed the application launch event to compile the application:

public partial class App : Application, IPartImportsSatisfiedNotification
{
    {...}

    private void App_Startup(object sender, StartupEventArgs e)
    {
        this.Compose();
    }

    public void Compose()
    {
        try
        {
            globalCatalog.Catalogs.Add(new DirectoryCatalog(extensionsDirectoryPath));
            CompositionContainer container = new CompositionContainer(globalCatalog);
            container.ComposeParts(this);
        }
        catch (Exception ex)
        {
            // Do something
        }
    }

    {...}
}

In fact, when the debugging and viewing of objects after import is performed, everything is hierarchically composed as desired. But when I try to show the MainWindow of the application, an exception is thrown on a call to MainWindow.Show ():

"The specified element is already a logical descendant of another element. First disable it."

OnImportsSatisfied , , Mecanism MEF:

public void OnImportsSatisfied()
{
    Window mainWindow = new Window();
    mainWindow.Content = this.importedControl;
    this.MainWindow = mainWindow;
    this.MainWindow.Show();
}

, , MEF. , :

Window mainWindow = new Window();
//mainWindow.Content = this.importedControl;
this.MainWindow = mainWindow;
this.MainWindow.Show();

, ComposeParts , , , .

, - (?). .


Edit:

, IPartImportsSatisfiedNotification , . , , , OnImportsSatisfied, DataContext .

+3
2

- , WPF ImportAttribute , , . , , , WPF ( ).

, RequiredCreationPolicy, NonShared, ! MEF...

0
+1

Source: https://habr.com/ru/post/1754779/


All Articles