如何使我的 WPF MainWindow 成为单例? [英] How to make my WPF MainWindow a singleton?

查看:50
本文介绍了如何使我的 WPF MainWindow 成为单例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的 MainWindow 成为单例,因为我想让我的应用程序中的所有其他窗口更容易访问它.但我无法让它运行.这是我所做的.

I want to make my MainWindow a singleton because I want to make accessing it from all other windows in my app easier. But I couldn't make it run. Here is what I did.

像往常一样,我将 MainWindow 承包商设为私有,并创建了一个 public static MainWindow Instance 属性来返回一个静态实例.当我在没有任何其他更改的情况下运行它时,出现无源可用"错误.我在互联网上搜索了一个相关主题 http://www.netframeworkdev.com/windows-presentation-foundation-wpf/xamlc-singleton-class-80578.shtml.但是,我无法按照那里的建议工作.有些人建议从

As usual, I made the MainWindow contractor private, and created a public static MainWindow Instance property to return a static instance. When I just run it without any other changes, I got "No Source Available" error. I googled the Internet and found one related topic at http://www.netframeworkdev.com/windows-presentation-foundation-wpf/xamlc-singleton-class-80578.shtml. However, I couldn't make it work as suggested there. Some suggest to make a change in MainWindow.xaml from

<Window x:Class="TestApp.MainWindow"

<Window x:Class="TestApp.MainWindow.Instance"

这看起来合乎逻辑.但是,当我这样做时,我遇到了大量的编译错误(第一个说命名空间 TestApp 已经包含了MainWindow"的定义.)

Which looks logical. However, when I did this, I got tons of compiling errors (first one says the namespace TestApp already contains a definition of 'MainWindow'.)

我在网上找到了很多关于如何制作单实例应用程序的文章.我不是在找这个.我只是想让我的 MainWindow 成为单例.我已经在 WinForm 应用程序中做过很多次了.

I found many articles on the Internet about how to make single instance app. I'm not looking for this. I just want to make my MainWindow a singleton. I have done it in WinForm apps many times.

推荐答案

要使 MainWindow 成为单例,您需要执行以下步骤:添加一个 MainWindow InstanceMainWindow 类...

To make the MainWindow a singleton, these are the steps you need to make: Add a MainWindow Instance to MainWindow class...

public static MainWindow Instance { get; private set; }

注意:set accessor 是私有的,所以没有人可以将它设置为其他任何东西.

Note: set accessor is private so that nobody else can set it to anything else.

MainWindow中添加一个静态构造函数,将MainWindow的构造函数设为private,像这样...

Add a static constructor in MainWindow and make the constructor of MainWindow private, like this...

static MainWindow()
{
    Instance = new MainWindow();
}

private MainWindow()
{
    InitializeComponent();
}

现在从您的 App.xaml 文件中删除 StartupUri="MainWindow.xaml" 以便在您启动应用程序时不会启动默认窗口.在 App.xaml.cs 中捕获您的 App 类的启动事件,如下所示:

Now remove StartupUri="MainWindow.xaml" from your App.xaml file so that no default window is launched when you start the application. Catch the Startup event of your App class in App.xaml.cs like this:

public App()
{
    ...
    Startup += App_Startup;
    ...
}

void App_Startup(object sender, StartupEventArgs e)
{
    TestApp.MainWindow.Instance.Show();
}

这篇关于如何使我的 WPF MainWindow 成为单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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