开发者

User Control - Custom Properties

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 con开发者_运维技巧trol 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜