5

I need to get a reference to the parent Microsoft.UI.Xaml.Window for a Control. Is there a way to do that in Project Reunion 0.5? Window.Current does not work in a desktop app.

David Brown
  • 35,411
  • 11
  • 83
  • 132
  • Have you looked at [VisualTreeHelper.GetParent](https://learn.microsoft.com/en-us/windows/winui/api/microsoft.ui.xaml.media.visualtreehelper.getparent?view=winui-3.0)? – Trevor Jun 08 '21 at 20:29
  • 1
    Yes, unfortunately `Window` is not part of the visual tree. – David Brown Jun 08 '21 at 20:36

1 Answers1

0

I do not know how to obtain the reference to a controls parent. But what you could do is have a static reference to your root window in the App class. Then you could read this reference in your project that represents the UI layer.

Example:

Let's say you are using this class as top level window:

/// <summary>
/// An empty window that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class YourWindowClass : Window
{
    public YourWindowClass()
    {
        this.InitializeComponent();
    }   
}

Then you could instanciate this class in your App class like this (see TopLevelWindow property):

/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public partial class App : Application
{    

    public App()
    {
        this.InitializeComponent();
    }    


    public static YourWindowClass TopLevelWindow { get; } = new YourWindowClass() { Title = "Window Title..." };


    protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
    {
        TopLevelWindow.Activate();
    }
} 

And to use the reference to the top level window, you could write this anywhere in your UI project:

App.TopLevelWindow
Martin
  • 5,165
  • 1
  • 37
  • 50