开发者

How to prevent a consumer of a UserControl from seeing the control's child controls?

if, in C#, you create a Windows UserControl, the "child" controls of that UserControl are e开发者_JAVA百科xposed via the "Controls" collection. That's to say, a consumer of your user control can refer to the Controls collection and gain access to the inner controls.

Is there a way to compartmentalise such a design so that the consumer cannot access anything which has not been explicitly exposed by the designer of the UserControl ?

Example: I have a user control which, internally, has two TextBox controls. A consumer of my UserControl can write the following:

MyControl1.Controls[0].Enabled = false;

Is there a way (for example) of having the "Controls" property return an empty collection so that the consumer cannot fiddle with the inner workings of the user control ?

It would seem reasonable that the UserControl should expose almost all properties which a "Control" would expose, but not the collections which give access to its inner workings.

Thanks, Ross


Don't know if this would work in all cases, but it seems to in a very simple test.

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

Of course, care would be needed should the user control want to access its own "Controls" collection (and would have to use base.Controls).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜