用户控制 - 自定义属性

jay*_*t55 69 c# user-controls properties winforms

我在Visual Studio中开发了一个用户控件(WinForms C#)并且有一个问题.

我需要我的用户控件的用户能够更改某些字符串值,我希望他们能够将用户控件添加到他们的表单并单击它以显示我的用户控件的自定义属性将在其中的属性窗格显示.

如何为用户控件设置自己的自定义属性?例如:

我的用户控件包含一个TextBox,我希望用户能够通过Design-Time属性中名为"Text"或"Value"的属性更改该TextBox的值.

Nic*_*ver 103

您可以通过属性上的属性执行此操作,如下所示:

[Description("Test text displayed in the textbox"),Category("Data")] 
public string Text {
  get { return myInnerTextBox.Text; }
  set { myInnerTextBox.Text = value; }
}
Run Code Online (Sandbox Code Playgroud)

该类别是属性将在Visual Studio属性框中显示的标题. 这是一个更完整的MSDN参考,包括类别列表.

  • 每次我想使用此代码生成项目时,我的VS2010都会崩溃,无论是否包含System.ComponentModel:& (3认同)

Han*_*ant 44

这很简单,只需添加一个属性:

public string Value {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}
Run Code Online (Sandbox Code Playgroud)

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

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


Jas*_*ams 6

只需将公共属性添加到用户控件即可.

您可以添加[Category("MyCategory")][Description("A property that controls the wossname")]属性以使其更好,但只要它是公共属性,它应该显示在属性面板中.