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.
User Control properties are used to set the values of a User Control from the parent page.
CustomControl is a loosely coupled control w.r.t code and UI while UserControl is a tightly coupled control w.r.t code and UI. When using CustomControl UI can be changed in different projects but for a UserControl UI is fixed and can't have different looks in different project.
What Does Custom Control Mean? Custom control is a control that is not included in the . NET framework library and is instead created by a third-party software vendor or a user. Custom control is a concept used while building both Windows Forms client and ASP.NET Web applications.
On the menu bar, choose View > Properties Window. The Property Editor dialog box appears. In the text box in the Name column, specify the name of the property. For the Type field of the custom property, choose the appropriate data type.
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.
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; }
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With