How do I get a WinUI Control's parent Window?
Asked Answered
A

1

6

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.

Arsine answered 8/6, 2021 at 20:22 Comment(2)
Have you looked at VisualTreeHelper.GetParent?Insight
Yes, unfortunately Window is not part of the visual tree.Arsine
F
1

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 instantiate 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
Fae answered 25/7, 2022 at 13:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.