Reputation: 785
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
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
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