C# 用户控制 - 自定义属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2081953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:21:56  来源:igfitidea点击:

User Control - Custom Properties

c#winformsuser-controlsproperties

提问by jay_t55

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.

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

采纳答案by Nick Craver

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

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

[Description("Test text displayed in the textbox"),Category("Data")] 
public string Text {
  get { return 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.

类别是属性将出现在 Visual Studio 属性框中的标题。 这是更完整的 MSDN 参考,包括类别列表。

回答by Jason Williams

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 publicproperty it should show up in the property panel.

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

回答by Hans Passant

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 hidesit. You'll need to override the attributes to put it back in working order:

使用 Text 属性有点棘手,UserControl 类有意隐藏它。您需要覆盖属性以使其恢复正常工作状态:

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