简体   繁体   English

用户控制 - 自定义属性

[英]User Control - Custom Properties

I have developed a User Control in Visual Studio (WinForms C#) and have a question.我在 Visual Studio (WinForms C#) 中开发了一个用户控件并有一个问题。

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.我的用户控件包含一个文本框,我希望用户能够在设计时通过属性中名为“文本”或“值”的属性更改该文本框的值。

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.类别是属性将出现在 Visual Studio 属性框中的标题。 Here's a more complete MSDN reference , including a list of categories. 这是更完整的 MSDN 参考,包括类别列表。

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.使用 Text 属性有点棘手,UserControl 类有意隐藏它。 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.您可以添加[Category("MyCategory")][Description("A property that controls the wossname")]属性以使其更好,但只要它是公共属性,它就应该显示在属性面板中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM