Saturday, April 25, 2009

Getting Parent Window for UserControl in WPF

Again a small item that may take you some time to search and find on the internet. Suppose you are working on a WPF based application and you have a UserControl that you want to host inside of a window. In addition you need the window within which the UserControl is hosted. To find out that parent window you might wonder whether you could use the property 'Parent'. Well that might work in some cases but in other cases it might not. For example the parent might be a Canvas and then it starts to become tricky. So here is a solution that should make it a bit easier. It uses the static method Window.GetWindow() and passes a reference to the UserControl instance as a parameter:
   public partial class FooControl : UserControl {
      public FooControl() {
         InitializeComponent();
      }

      private void _barButton_Click(object sender, RoutedEventArgs e) {
         var window = new MyWindow {
            WindowStartupLocation = WindowStartupLocation.CenterOwner,
            Owner = Window.GetWindow(this)
         };
         if( window.ShowDialog() == true) {
            // Ok button clicked, do something useful here...
         }
      }
   }

9 comments:

Alex Martsynkevich said...

This won't work, if you're hosting your element in System.Windows.Forms.Integration.ElementHost.
Window.GetWindow(this) returns null and clicking on parent form in task bar will hide your modal dialog confusing the hell out of user.

Any ideas how to find parent's HWND? Then it supposedly a matter of doing

new WindowInteropHelper(window).Owner = hwnd;

... before window.ShowDialog()

Thanks

Alex Martsynkevich said...

Just found a way to set an Owner for visuals hosted in ElementHost. Here's my helper function:

public static void SetWindowOwner(Visual visual, Window window)
{
var parent = Window.GetWindow(visual);
if (parent != null)
window.Owner = parent;
else
{
var source = (HwndSource) PresentationSource.FromVisual(visual);
if (source != null)
new WindowInteropHelper(window).Owner = source.Handle;
}
}

Cheers!

Anonymous said...

thank you. This saved my time and this works for me.
B

Anonymous said...

Thank you very much for that !!! It's exactly what we need !!!

Anonymous said...

I forwarded it to my blog and put this link as a reference. Thanks :)

Anonymous said...

this was really useful! It was exactly what i was looking for.

Anonymous said...

Thanks..it is really helpful.

dddd said...

good work.

Byju Abraham said...

Thanks. It woked

Post a Comment

All comments, questions and other feedback is much appreciated. Thank you!