WPF: How do I set the Owner Window of a Dialog shown by a UserControl?

Zack Peterson picture Zack Peterson · Mar 3, 2009 · Viewed 81.4k times · Source

I've got a WPF application with these three types of things...

  • WindowMain
  • UserControlZack
  • WindowModal

UserControlZack1 sits on my WindowMain...

<Window x:Class="WindowMain"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ProjectName"
        ...
        Name="WindowMain">
    <Grid>
        ...
        <local:UserControlZack x:Name="UserControlZack1" ... />
        ...
    </Grid>
</Window>

UserControlZack1 displays a WindowModal dailog box...

Partial Public Class UserControlZack

   ...

    Private Sub SomeButton_Click(...)
        'instantiate the dialog box and open modally...
        Dim box As WindowModal = New WindowModal()
        box.Owner = ?????
        box.ShowDialog()
        'process data entered by user if dialog box is accepted...
        If (box.DialogResult.GetValueOrDefault = True) Then
            _SomeVar = box.SomeVar
            ...
        End If
    End Sub

End Class

How do I set box.Owner to the correct Window, my running instance of WindowMain?

I cannot use box.Owner = Me.Owner, because "'Owner' is not a member of 'ProjectName.UserControlZack'."

I cannot use box.Owner = Me.Parent, because that returns a Grid, not the Window.

I cannot use box.Owner = WindowMain, because "'WindowMain' is a type and cannot be used as an expression."

Answer

Martin Moser picture Martin Moser · Mar 4, 2009

Try to use

.Owner = Window.GetWindow(this)