简体   繁体   English

WinForms中的设计时范围

[英]Designtime scope in winforms

I have a question about how to setup components in a winforms application so they can interact with each other. 我有一个关于如何在Winforms应用程序中设置组件以便它们可以相互交互的问题。 But I want to use the visual designer to set this up. 但我想使用视觉设计师进行设置。

What I have is a component called myDataBase and a component called myDataTable. 我所拥有的是一个名为myDataBase的组件和一个名为myDataTable的组件。
Now the component myDataTable has a property of type myDataBase. 现在,组件myDataTable具有类型为myDataBase的属性。 So in code I can do 所以在代码中我可以做

myDataBase db = new myDataBase();
myDataTable dt = new myDataTable();
dt.DataBase = db;

The property DataBase in component myDataTable is public, so I can also use the visual designer to assign the DataBase property. 组件myDataTable中的属性DataBase是公共的,因此我也可以使用可视设计器来分配DataBase属性。

在此处输入图片说明

Now for my problem. 现在我的问题。 I have many many forms that have one or more components of myDataTable on it. 我有很多形式都有myDataTable的一个或多个组件。
I only want one instance for myDataBase. 我只需要一个myDataBase实例。

What I do now is I create a component myDataBase dbMain = new myDataBase() on the mainform. 我现在要做的是在主窗体上创建一个组件myDataBase dbMain = new myDataBase()。
On every form I have to set the property for all myDataTable components to this dbMain. 在每种表单上,我都必须将所有myDataTable组件的属性设置为此dbMain。
I have to do this in code because the visual designer cannot see the dbMain component on the mainform. 我必须在代码中执行此操作,因为可视设计器无法在主窗体上看到dbMain组件。

So the question is, can I create one instance of component myDataBase that is visible to the visual designer on all forms, so I can use the visual designer to set the property of myDataTable components ? 所以问题是,我可以创建一个组件myDataBase的实例,该实例对于所有形式的可视化设计器都是可见的,以便可以使用可视化设计器设置myDataTable组件的属性?

For those that now Delphi, I want something like the DataModule in Delphi. 对于那些现在的Delphi,我想要类似Delphi中的DataModule的东西。

You can't without some code. 您不能没有一些代码。

The easiest thing you can do, as far as I am concerned, it to create a base form, deriving from Form , and in that form, you make a property pointing to a singleton instance of your database object. 就我而言,您可以做的最简单的事情是创建一个从Form派生的基本Form ,并在该表单中创建一个指向数据库对象的单例实例的属性。 You can bind to that property, and still keep it as simple as possible. 您可以绑定到该属性,并且仍然使其尽可能简单。

You just need to make your form derive from this one: 您只需要使您的表格派生自此表格即可:

public class DatasourceForm : Form
{
    public myDataBase DataBase
    {
        get
        {
            return myDataBaseFactory.Current;
        }
    }
}

And the factory in charge of creating the singleton database instance: 负责创建单例数据库实例的工厂:

public class myDataBaseFactory
{
    private static readonly Lazy<myDataBase> lazy =
    new Lazy<myDataBase>(() => new myDataBase());

    public static myDataBase Current { get { return lazy.Value; } }
}

(Singleton implementation from here ) (从这里开始实现)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM