简体   繁体   中英

Designtime scope in winforms

I have a question about how to setup components in a winforms application so they can interact with each other. 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.
Now the component myDataTable has a property of type 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.

在此处输入图片说明

Now for my problem. I have many many forms that have one or more components of myDataTable on it.
I only want one instance for myDataBase.

What I do now is I create a component myDataBase dbMain = new myDataBase() on the mainform.
On every form I have to set the property for all myDataTable components to this dbMain.
I have to do this in code because the visual designer cannot see the dbMain component on the mainform.

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 ?

For those that now Delphi, I want something like the DataModule in Delphi.

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. 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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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