In most of these cases I have my WPF user controls binding to commands on my
view models and passing the UserControl or Window they're in as a parameter
(via FindAncestor).

I have a couple of utility methods that the view models can then call to set
the owner for a given Window based on whatever is hosting a given
DependencyObject, and this uses the following code to get the hosting Window
/ Form:

                var hostWindow = Window.GetWindow(dependencyObject);
                if (hostWindow != null)
                {
                    return hostWindow;
                }
                else
                {
                    // Check if the owner is hosted on a Form
                    var source =
PresentationSource.FromDependencyObject(dependencyObject) as
HwndSource;
                    if (source != null)
                    {
                        ElementHost host =
System.Windows.Forms.Control.FromChildHandle(source.Handle) as
ElementHost;
                        // Get the form
                        var parent = host.Parent;
                        while (parent != null && !(parent is Form))
                        {
                            parent = parent.Parent;
                        }
                        return parent;
                    }
                    else
                    {
                        return null;
                    }
                }

Unfortunately, this doesn't help with the WPF MessageBox as it will only
take a Window as it's owner.  Until I get rid of the WinForms stuff I have
to use the WinForms MessageBox which can take a IWin32Window as it's owner
so I can use either a Form or a Window.

As a side note, this is my first real WPF app and I'm not real happy with
having the view models create and show my custom dialogs - this feels like
something that the view should do in response to an event or something from
the view model, but then maybe I'm just not getting MVVM...

On Thu, Nov 18, 2010 at 8:25 AM, Greg Keogh <[email protected]> wrote:

> Matt, did you ever find a way of getting the WPF Window for a WPF control
> hosted inside a parent Form? Sorry, it was the reverse of what I had in
> mind.
>
>
>
> In my earlier Apps that were hybrids like yours I was lazy and avoided the
> problem by having the WPF children send a message to the parent Form to
> actually do a MessageBox Show on their behalf.
>
>
>
> Greg
>

Reply via email to