Search code examples
c#wpfstaticreferencewindow

How to get a static reference to a WPF Window?


I've tried a huge amount of ways to get a static reference of my window across my program. I need to access all of its members at runtime from different classes, so a static reference is needed.

What I'd like to have is something like Program.Window1, where Core is static and MyWindow is one of its static members.

In WinForms, I usually declare my static form in Program.cs, but this does not seem to work with WPF and their custom "App.xaml" ApplicationDefinition.

How can I do it?

Note: I have tried a number of ways already: using a direct call to a new window (i.e. Program.Window1 = new Window1()) will not work, as I get some thread invalidity exception. As I understand so far, only ApplicationDefinitions can launch windows in WPF.

Here is the exception whenever I try to create a window "by code" and not by the default XAML ApplicationDefinition's StartupUri:

The calling thread must be STA, because many UI components require this.


Solution

  • Create a static class that can contain the window object, and then when the window is created, have it pass itself to the static class, from then on the static class can hand out the window object to interested parties even though the window object itself is not static. Something like this. There is no need for your form to be static, you just need a static place to hold the form object.

    public class Core
    {
         internal static MyWindowClass m_Wnd = null;
    
         // call this when your non-static form is created
         //
         public static void SetWnd(MyWindowClass wnd)
         {
             m_Wnd = wnd;
         }
    
         public static MyWindow { get { return m_Wnd; } }
    }