簡體   English   中英

如何防止UserControl的使用者看到控件的子控件?

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

如果在C#中創建Windows UserControl,則該UserControl的“子級”控件通過“ Controls”集合公開。 也就是說,用戶控件的使用者可以引用控件集合並獲得對內部控件的訪問權限。

有沒有辦法分隔這種設計,以使消費者無法訪問UserControl設計者未明確公開的任何內容?

示例:我有一個用戶控件,在內部有兩個TextBox控件。 我的UserControl的使用者可以編寫以下內容:

MyControl1.Controls[0].Enabled = false;

是否有一種方法(例如),使“控件”屬性返回一個空集合,從而使消費者無法擺弄用戶控件的內部工作原理?

UserControl應該公開幾乎所有“ Control”將公開的屬性,但不能公開提供對其內部工作的訪問的集合,這似乎是合理的。

謝謝羅斯

不知道這是否在所有情況下都能奏效,但這似乎在一個非常簡單的測試中。

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),則需要小心

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM