How to get a static reference to a WPF Window?

后端 未结 4 1521
醉酒成梦
醉酒成梦 2021-01-12 05:39

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 stati

4条回答
  •  余生分开走
    2021-01-12 06:13

    I have used this with success. Declare a static variable of the window type. Then in the constructor of the window set the static variable to "this". I have used it throughout the app and it seems to be working fine from within static or instance methods.

        public static MainWindow screenMain = null;
        public MainWindow()
        {
            InitializeComponent();
    
            screenMain = this;  //static reference to this.
    
        }
    

    For instance I am able to do this.

        private delegate void del();
        ....
        screenMain.Dispatcher.Invoke(new del(delegate()
        {
            screenMain.ButtonSubmit.IsEnabled = true;
            screenMain.ButtonPreClearing.IsEnabled = true;
        }));   
    

提交回复
热议问题