【问题标题】:Initialize container from Control从 Control 初始化容器
【发布时间】:2011-07-18 17:31:21
【问题描述】:

我有这个代码:

    public class Configuration{

        public Control container;

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

        }
    }

并且我想在 Configuration 的构造函数中初始化控制的容器,我希望能够像这样将组件添加到容器中:

container.Container.Add(someComponente);

确保容器已经初始化。

如何做到这一点?

【问题讨论】:

    标签: c# controls containers


    【解决方案1】:

    使用“延迟加载”技术。

    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());
    

    【讨论】:

      【解决方案2】:

      使用 Loaded 事件处理程序来执行您的代码:

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

      此示例使用匿名方法,但当然您也可以使用通常的处理程序。

      【讨论】:

        猜你喜欢
        • 2012-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多