开发者

Initialize container from Control

I have this code:

    public class Configuration{

        public Control container;

        public Configuration()
        {
            container = new Control();

        }
    }

and i want to i开发者_Python百科nitialize in the constructor of Configuration the contrainer of control, i wanna be able to add componentes to the container like this:

container.Container.Add(someComponente);

With the assurance that the Container has already been initialized.

How to accomplish this?


Use "lazy-loading" technique.

public class Configuration {
    private Control container;
    public Control Container {
        get {
            var result = this.container;
            if ( null == result ) {
                this.container = result = new Container();
            }
        }
        set { this.container = value; }
    }
}

// ... elsewhere ...
var cfg = new Configuration();
cfg.Container.Controls.Add(new Button());


Use the Loaded event handler to execute your code:

container.Loaded += (s, e) =>
{
    // do something
};

This example is using an anonymous method, but of course you can use the usual handler as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜