User Control - Custom Properties

C#WinformsUser ControlsProperties

C# Problem Overview


I have developed a User Control in Visual Studio (WinForms C#) and have a question.

I need the user of my User Control to be able to change certain string values and I would like them to be able to add the user control to their Form and click on it to bring up the Properties Pane where my User Control's custom properties will be displayed.

How can I have my own custom properties for my user control? For example:

My user control contains a TextBox, and I would like the user to be able to change the value of that TextBox via a property named "Text" or "Value" in the properties at Design-Time.

C# Solutions


Solution 1 - C#

You do this via attributes on the properties, like this:

[Description("Test text displayed in the textbox"),Category("Data")] 
public string Text {
  get => myInnerTextBox.Text;
  set => myInnerTextBox.Text = value;
}

The category is the heading under which the property will appear in the Visual Studio Properties box. Here's a more complete MSDN reference, including a list of categories.

Solution 2 - C#

It is very simple, just add a property:

public string Value {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:

[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Solution 3 - C#

Just add public properties to the user control.

You can add [Category("MyCategory")] and [Description("A property that controls the wossname")] attributes to make it nicer, but as long as it's a public property it should show up in the property panel.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjay_t55View Question on Stackoverflow
Solution 1 - C#Nick CraverView Answer on Stackoverflow
Solution 2 - C#Hans PassantView Answer on Stackoverflow
Solution 3 - C#Jason WilliamsView Answer on Stackoverflow