Search code examples
c#wpf

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?


Solution

  • 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.