Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 779
Zack Peterson Avatar asked Mar 03 '09 17:03

Zack Peterson


People also ask

What is the difference between UserControl and window in wpf?

A window is managed by the OS and is placed on the desktop. A UserControl is managed by wpf and is placed in a Window or in another UserControl. Applcations could be created by have a single Window and displaying lots of UserControls in that Window.

How can I access a control in wpf from another class or window?

Access of the controls from within the same assembly is hence allowed. If you want to access a control on a wpf form from another assembly you have to use the modifier attribute x:FieldModifier="public" or use the method proposed by Jean.

How do I close a Windows UserControl wpf?

or by simply: var myWindow = Window. GetWindow(this); myWindow. Close();


2 Answers

Try to use

.Owner = Window.GetWindow(this) 
like image 94
Martin Moser Avatar answered Sep 23 '22 04:09

Martin Moser


To get the top level window your control is in, assuming there is one:

(Window)PresentationSource.FromVisual(this).RootVisual 

To get the main window:

Application.Current.MainWindow 
like image 41
Nir Avatar answered Sep 20 '22 04:09

Nir