Home > OS >  Avalonia Get All Windows
Avalonia Get All Windows

Time:12-07

Is there a way to get a list of all windows in Avalonia?

The equivalent of this in WPF

Application.Current.Windows

My requirement is to activate or close a certain window based on its DataContext.

If I can't access such a list; is there a way to track the creation and destruction of windows to create an internal list?

CodePudding user response:

you can create WindowsManagerClass with one static propery with type of List<Window> like this

 public class WindowsManager
    {
        public static List<Window> AllWindows = new List<Window>();
    }

and add to AllWindows like this code in your Form constructor

 public MainWindow()
        {
            InitializeComponent();
            WindowsManager.AllWindows.Add(this);
        }

and where you need you can access reference like this

var allwindows = WindowsManager.AllWindows;

            var selectedWindows = allwindows.FirstOrDefault(x => x.Name == "Test");
            if (selectedWindows != null)
            {
                if (selectedWindows.IsActive)
                {
                    selectedWindows.Close();
                }
            }

Full form code (in this example when you click button form will be close)

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            WindowsManager.AllWindows.Add(this);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var allwindows = WindowsManager.AllWindows;

            var selectedWindows = allwindows.FirstOrDefault(x => x.Name == "");
            if (selectedWindows != null)
            {
                if (selectedWindows.IsActive)
                {
                    selectedWindows.Close();
                }
            }
        }
    }

CodePudding user response:

You need IClassicDesktopStyleApplicationLifetime::Windows property. Lifetime is available from Application's ApplicationLifetime property.

e. g.

((IClassicDesktopStyleApplicationLifetime)Application.Current.ApplicationLifetime).Windows

Note that it's not available for Mobile, WebAssembly and Linux framebuffer platforms.

  • Related