2
votes

if, in C#, you create a Windows UserControl, the "child" controls of that UserControl are exposed 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

1

1 Answers

0
votes

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