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."
What about changing the name of the window to WindowMain1 or something, and setting the owner to that?
To get the top level window your control is in, assuming there is one:
To get the main window:
Try to use
Updating to try and help Greg from the comments. The command works in the main windows menu, the button in the user control and the context menu in the user control.
I'd do it with commands. So have a class Commands.cs something like:
Register these in your main window: (you don't need the canshow it defaults to true)
This is my xaml for the main window:
This is the xaml for my user control (default code behind only)
You could take it a bit further and handle the command in a controller class instead and make it that bit more MVC.
I got it to work by crawling all the way back up through my XAML...
But this seems quite inelegant. Is there a better way?