How to set .Owner to Shell for a new Window

Sep 25, 2008 at 5:10 PM
I have a module were I show a new window. How do I get hold of the Shell instance to set the corresponding Window.Owner property?
Sep 26, 2008 at 11:27 AM
I would use the following 4 steps:

1.  create an interface in one of my infrastructure interface libraries

public interface IShell {}

2. Update my Shell to implement the interface

public partial class Shell : Window, IShell
{
    public Shell()
    {
        InitializeComponent();
    }
}

3. Update my BootStrapper.cs to resolve the interface

protected override DependencyObject CreateShell()
{
    Container.RegisterType<IShell, Shell>();
    Shell shell = (Shell)Container.Resolve<IShell>();
    shell.Show();
    return shell;
}

4.  From the applicable module resolve and cast to get my Window reference

[Dependency]
public IShell Shell { get; set; }

public void Initialize()
{
    Window shell = (Window)Shell;
    ...
    ...
}
Sep 26, 2008 at 12:49 PM
Thankx BillKrat. Your steps are well document and I have implemented it (I just learned a lot about Dependency Property!).

I do get the shell instance, but when I do the following statement

view.Owner = (Window)this.Shell;

it crashes with the following message:

"Cannot set Owner property to a Window that has not been shown previously"

The Window is definitly there since I use a MenuItem, which then uses an Event to call the function.
(The code where the view.Owner = (Window)this.Shell; is within the EventHandler.)
Could that be the reason?
Sep 26, 2008 at 1:38 PM
It is working now. In step 3 above, I change the following
from
    Container.RegisterType<IShell, Shell>();
to
    Container.RegisterType<IShell, Shell>(new ContainerControlledLifetimeManager());

Thankx, again!
Sep 26, 2008 at 8:16 PM
Right, that should do the trick.
But if you want to further abstract where you are showing your views, you could use a region adapter for displaying the views that are in a region in separate windows.
Ignacio Baumann has written sample code on how to achieve this here: WindowRegionAdapter for CompositeWPF (Prism)

This way you add your view as you would do it with any other region.

Julian Dominguez
http://blogs.southworks.net/jdominguez
Oct 20, 2008 at 12:47 PM
Edited Oct 20, 2008 at 12:48 PM
I just learned that one can do the following (where this is a View):

 

public XxxxxView()

 

{

InitializeComponent();

 

this.Owner = Application.Current.MainWindow;

 

}