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() {

      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...


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()


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;
var source = (HwndSource) PresentationSource.FromVisual(visual);
if (source != null)
new WindowInteropHelper(window).Owner = source.Handle;


Anonymous said...

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

Thank you very much for that !!! It's exactly what we need !!! 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... is really helpful.

Post a Comment

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