如何获取对 WPF 窗口的静态引用? [英] How to get a static reference to a WPF Window?

查看:52
本文介绍了如何获取对 WPF 窗口的静态引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了大量方法来在我的程序中获取我的窗口的静态引用.我需要在运行时从不同的类访问它的所有成员,因此需要一个静态引用.

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.

我想要的是类似于 Program.Window1 的东西,其中 Core 是静态的,而 MyWindow 是它的静态成员之一.

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

在 WinForms 中,我通常在 Program.cs 中声明我的静态表单,但这似乎不适用于 WPF 及其自定义的App.xaml"ApplicationDefinition.

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.

我该怎么做?

注意:我已经尝试了多种方法:使用直接调用新窗口(即 Program.Window1 = new Window1())将不起作用,因为我得到了一些线程无效例外.据我所知,目前只有 ApplicationDefinitions 可以在 WPF 中启动窗口.

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.

每当我尝试通过代码"而不是通过默认的 XAML ApplicationDefinition 的 StartupUri 创建窗口时,都会出现异常:

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

调用线程必须是 STA,因为很多 UI 组件都需要这个.

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

推荐答案

创建一个可以包含窗口对象的静态类,然后在创建窗口的时候,让它把自己传递给静态类,从此静态即使窗口对象本身不是静态的,类也可以将窗口对象分发给感兴趣的各方.像这样的东西.你的表单不需要是静态的,你只需要一个静态的地方来保存表单对象.

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; } }
}

这篇关于如何获取对 WPF 窗口的静态引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆