<p>您可以按照以下简单步骤轻松创建自己的字符串集合编辑器。<em>本例使用C#。</em></p>
<p>1)必须创建一个编辑器控件并从<code>System.Drawing.Design.UITypeEditor</code>派生它。我打电话给我的。所以我的课从</p>
<pre><code>public class StringArrayEditor : System.Drawing.Design.UITypeEditor
</code></pre>
<p><code>PropertyGrid</code>控件需要知道编辑器是模态的,并且当选择相关属性时,它将显示省略号按钮。因此您必须重写<code>GetEditStyle</code>,如下所示:</p>
^{pr2}$
<p>最后,editor控件必须重写<code>EditValue</code>操作,这样当用户单击属性的省略号按钮时,它就知道要如何继续。以下是覆盖的完整代码:</p>
<pre><code> public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
var editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
if (editorService != null)
{
var selectionControl = new TextArrayPropertyForm((string[])value, "Edit the lines of text", "Label Editor");
editorService.ShowDialog(selectionControl);
if (selectionControl.DialogResult == DialogResult.OK)
value = selectionControl.Value;
}
return value ?? new string[] {};
}
</code></pre>
<p>发生了什么事?当用户单击省略号时,将调用此重写。<code>editorService</code>被设置为我们编辑表单的接口。它被设置为我们尚未创建的形式,我称之为<code>TextArrayPropertyForm</code>。<code>TextArrayPropertyForm</code>被实例化,传递要编辑的值。为了更好地度量,我还传递了两个字符串,一个用于表单标题,另一个用于顶部的标签,用于解释用户应该做什么。它是以模式显示的,如果单击了OK按钮,那么该值将更新为我们将创建的表单中<code>selectionControl.Value</code>中设置的值。最后,在重写结束时返回该值。在</p>
<p>步骤2)创建编辑器表单。在我的例子中,我创建了一个包含2个按钮(<code>buttonOK</code>和<code>buttonCancel</code>)、标签(<code>labelInstructions</code>)和文本框(<code>textValue</code>)的表单,以模拟默认的StringCollection编辑器。代码非常简单,但是如果您感兴趣,就在这里。在</p>
<pre><code>using System;
using System.Windows.Forms;
namespace MyNamespace
{
/// <summary>
/// Alternate form for editing string arrays in PropertyGrid control
/// </summary>
public partial class TextArrayPropertyForm : Form
{
public TextArrayPropertyForm(string[] value,
string instructions = "Enter the strings in the collection (one per line):", string title = "String Collection Editor")
{
InitializeComponent();
Value = value;
textValue.Text = string.Join("\r\n", value);
labelInstructions.Text = instructions;
Text = title;
}
public string[] Value;
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
private void buttonOK_Click(object sender, EventArgs e)
{
Value = textValue.Text.Split(new[] { "\r\n" }, StringSplitOptions.None);
DialogResult = DialogResult.OK;
}
}
}
</code></pre>
<p>步骤3)告诉PropertyGrid使用备用编辑器。此属性与PropertyGrid控件中使用的任何其他属性之间的更改是[Editor]行。在</p>
<pre><code> [Description("The name or text to appear on the layout.")]
[DisplayName("Text"), Browsable(true), Category("Design")]
[Editor(typeof(StringArrayEditor), typeof(System.Drawing.Design.UITypeEditor))]
public string[] Text {get; set;}
</code></pre>
<p>现在,当您在窗体上创建PropertyGrid并设置为包含此文本属性的类时,它将在您的自定义窗体中进行编辑。有无数的机会来改变你的定制形式,你选择的方式。经过修改,这将适用于编辑任何你喜欢的类型。重要的是编辑器控件返回的类型与被重写的<code>EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)</code>中的属性相同</p>
<p>希望这有帮助!在</p>