user713813
user713813

Reputation: 785

wpf c# public var of Application.Current.Windows

I have multiple windows in my wpf app. Im finding that I have to constantly reference those windows inside various private functions like this:

var P1 = Application.Current.Windows
        .Cast<Window>()
        .FirstOrDefault(window => window is Player1Screen) as Player1Screen;

What is the easiest way to declare this once and then access it everywhere?

Upvotes: 0

Views: 1845

Answers (2)

spender
spender

Reputation: 120400

If you want something a little more reusable, you could create an extension method to find the window...

public static class AppEx
{
    public static T FindWindowOfType<T>(this Application app) where T:Window
    {
        return app.Windows.OfType<T>().FirstOrDefault();
    }
}

so now:

Player1Screen win = Application.Current.FindWindowOfType<Player1Screen>();

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292405

You can expose it via a public static property in any class of your project (e.g. the App class):

public static Player1Screen Player1Screen
{
    get
    {
        return Application.Current.Windows
            .OfType<Player1Screen>()
            .FirstOrDefault();
    }
}

Note that I simplified the code a bit.

Upvotes: 1

Related Questions