简体   繁体   中英

How to get collection of all active wpf windows (multithreading) if Apllication.Current is NULL?

In my project i programmatically create couple wpf windows from class in different threads. In one of this wpf windows code (xaml.cs) I want to get all active wpf windows using System.Windows.Application.Current.Windows but System.Windows.Application.Current is Null . How can i get this collection and is it really possible?

If you create windows on different threads for whatever reasons, you should keep track of them yourself. You could for example add them to a static collection that may be accessible from all threads, eg:

public class ApplicationService
{
    private readonly List<Window> _windows = new List<Window>();

    public IEnumerable<Window> Windows => _windows;

    public void Add(Window window)
    {
        if (window == null)
            throw new ArgumentNullException(nameof(window));

        lock (_windows)
        {
            window.Closed += Window_Closed;
            _windows.Add(window);
        }
    }

    private void Window_Closed(object sender, EventArgs e)
    {
        Window window = (Window)sender;
        lock (_windows)
        {
            window.Closed -= Window_Closed;
            _windows.Remove(window);
        }
    }
}

The Application.Current.Windows collection doesn't keep track of windows created on any other thread than the app's dispatcher thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM