如何在类之间共享用户控件的实例?

时间:2019-02-23 11:33:26

标签: c# winforms

首先,我对此并不太了解,对不起,请多多包涵。

比方说,我在设计屏幕的表单中有一个用户控件。这本身就是一个实例吗?如果是这样,如何在类之间轻松共享此实例?

我目前有一个单例类,这意味着我在为每个用户控件添加额外的实例。但是,当我通过单例类和.Show().Visible = true调用用户控件实例时,它不会出现。仅当我引用设计属性窗口中的用户控件名称时才出现(我猜这是第一个实例)。

此外,表单在加载应用程序时是否有其自己的实例,还是需要实例化?与用户控件相比,它们在实例化方面如何工作?

如果您需要代码,我会提供,但我认为这更多是我要提出的概念性问题。如果您可以提供示例代码,那就太好了。

编辑:

单班:

class Single
{
    public Form1 Form { get; private set; }
    public Menu MenuForm { get; private set; }
    public RandomFacts RandomFactsForm { get; private set; }
    public QuizMenu QuizMenuForm { get; private set; }
    public AskHowManyQuestions AskHowManyQuestionsForm { get; private set; }
    public QuizUC QuizUserControl { get; private set; }
    public QuizSetupUC QuizSetupUserControl { get; private set; }

    private static readonly Form1 _form1 = new Form1();
    private static readonly Menu _menu = new Menu();
    private static readonly RandomFacts _randomFacts = new RandomFacts();
    private static readonly QuizMenu _quizMenu = new QuizMenu();
    private static readonly AskHowManyQuestions _askHowManyQuestions = new AskHowManyQuestions();
    private static readonly QuizUC _quizUC = new QuizUC();
    private static readonly QuizSetupUC _quizSetupUC = new QuizSetupUC();

    private static readonly Single _single = new Single();

    private Single()
    {
        Form = _form1;
        MenuForm = _menu;
        RandomFactsForm = _randomFacts;
        QuizMenuForm = _quizMenu;
        AskHowManyQuestionsForm = _askHowManyQuestions;
        QuizUserControl = _quizUC;
        QuizSetupUserControl = _quizSetupUC;
    }

    public static Single GetSingle()
    {
        return _single;
    }
}

尝试从显示控件的表单中加载用户控件(无效):

private QuizSetupUC QuizSetupCon; // in scope of class

QuizSetupCon = Single.GetSingle().QuizSetupUserControl;
QuizSetupCon.Show();
QuizSetupCon.Location = new Point(40, 10);

但这可行(表单设计中用户控件的名称):

quizSetupUC1.Show();

0 个答案:

没有答案