How to Pass Ownership to a New Window

RogerSchlueter-7899 1,236 Reputation points
2023-03-08T21:34:14.4033333+00:00

My project has a window (called ChildWindow) that is opened from other windows. Some of the functionality contained in the view model of the ChildWindow depends on which window opened the ChildWindow.

Thus, in code-behind of the ChildWindow I have:

Public Sub New(Optional ownr As Window = Nothing)
    InitializeComponent()
	if ownr IsNot Nothing then Owner=ownr
End Sub

What I cannot figure out is how to make "Owner" available to the ChildWindow's view model.

Alternatively, I tried to make Owner a property of the ChildWindow in the ChildWindow's view model:

Private _owner As Window
Public Property Owner As Window
    Get
        Return _owner
    End Get
    Set(value As Window)
        _owner = value
    End Set
End Property

In this approach, I cannot figure out how to initialize the Owner property.

What is the best approach to this issue?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,676 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,579 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 48,581 Reputation points
    2023-03-08T22:02:34.3733333+00:00

    I would argue that if a view model needs to know about a UI element then it really isn't a view model anymore. The whole purpose of MVVM is to separate the V from the VM. I suspect if you rethink what you're trying to do you'll come up with a solution that doesn't require this approach. The best place to start is by looking at what you need from the parent window. Do you need to be notified when something happens? If so then expose a method on your child view model that the parent can hook into to notify it when needed. Do you need extra data from the parent window? Why not have the parent window pass that information to the child as part of the view model (perhaps as an interface containing the data)? Do you need to have the child notify the parent about a change? Expose an event on the child view model. It really depends on what you are trying to do as to which approach you go with.

    But let's suppose you really need the owner window. In a WPF Window you already have the Owner property that tells you who the owner is. You don't need to expose yet another property for it. Note that the owner of a window generally isn't set until the window is shown so ideally you would wait until the Activated event (?) is raised to do anything with the owner. You could, in the child window, then use the Owner property of the child window to pass along whatever you need into the viewmodel of the child.

    0 comments No comments