I've got a WPF application with these three types of things...
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."
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.
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.
or by simply: var myWindow = Window. GetWindow(this); myWindow. Close();
Try to use
.Owner = Window.GetWindow(this)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With