【问题标题】:How to prevent a consumer of a UserControl from seeing the control's child controls?如何防止 UserControl 的使用者看到控件的子控件?
【发布时间】:2011-07-29 07:11:12
【问题描述】:

如果在 C# 中创建一个 Windows 用户控件,则该用户控件的“子”控件通过“控件”集合公开。也就是说,您的用户控件的使用者可以引用 Controls 集合并获得对内部控件的访问权限。

有没有办法将这样的设计区分开来,使消费者无法访问用户控件设计者未明确公开的任何内容?

示例:我有一个用户控件,它在内部有两个 TextBox 控件。我的 UserControl 的使用者可以编写以下内容:

MyControl1.Controls[0].Enabled = false;

有没有办法(例如)让“Controls”属性返回一个空集合,这样消费者就不能摆弄用户控件的内部工作?

UserControl 应该公开几乎所有“控件”会公开的属性,而不是允许访问其内部工作的集合,这似乎是合理的。

谢谢, 罗斯

【问题讨论】:

    标签: c# user-controls


    【解决方案1】:

    不知道这是否适用于所有情况,但似乎在一个非常简单的测试中。

    public partial class UserControl1 : UserControl
    {
      private ControlCollection _controls;
    
      public UserControl1()
      {
         InitializeComponent();
    
         _controls = new ControlCollection(this);
      }
    
      new public ControlCollection Controls
      {
         get
         {
            return (_controls != null ? _controls : base.Controls);
         }
      }
    }
    

    当然,如果用户控件想要访问其自己的“控件”集合(并且必须使用 base.Controls),则需要小心。

    【讨论】:

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