How to access properties of a usercontrol in C#

前端 未结 5 1343
鱼传尺愫
鱼传尺愫 2020-12-06 09:58

I\'ve made a C# usercontrol with one textbox and one richtextbox.

How can I access the properties of the richtextbox from outside the usercontrol.

For exampl

5条回答
  •  粉色の甜心
    2020-12-06 10:12

    Cleanest way is to expose the desired properties as properties of your usercontrol, e.g:

    class MyUserControl
    {
      // expose the Text of the richtext control (read-only)
      public string TextOfRichTextBox
      {
        get { return richTextBox.Text; }
      }
      // expose the Checked Property of a checkbox (read/write)
      public bool CheckBoxProperty
      {
        get { return checkBox.Checked; }
        set { checkBox.Checked = value; }
      }
    
    
      //...
    }
    

    In this way you can control which properties you want to expose and whether they should be read/write or read-only. (of course you should use better names for the properties, depending on their meaning).

    Another advantage of this approach is that it hides the internal implementation of your user control. Should you ever want to exchange your richtext control with a different one, you won't break the callers/users of your control.

提交回复
热议问题