使用PropertyGrid控件,如果直接自定义一个show对象SomeProperties,然后propertyGrid1.SelectedObject = new SomeProperties();所有的属性都会以一行文本显示,如果有个属性可能出现文字较多的情况,那么一行文本显然是不够的,如下图,假设张三这里是上海市杨浦区国权路151号5号楼502室.....,
就需要和VS里面的文本框的text属性那样,当鼠标点击的时候,可以出现一个下拉的文本框,如下图:
首先自定义一个类,需要添加几个引用
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Drawing.Design;
namespace PorpertyGrid
{
/// <summary>
/// PropertyGridMutiText 的摘要说明。
/// </summary>
public class PropertyGridRichText : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.DropDown;
}
public override object EditValue(System.ComponentModel.ITypeDescriptorContext context,System.IServiceProvider provider,object value)
{
try
{
IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (edSvc != null)
{
if (value is string)
{
RichTextBox box = new RichTextBox();
box.Text = value as string;
edSvc.DropDownControl(box);
return box.Text;
}
}
}
catch (Exception ex)
{
System.Console.WriteLine("PropertyGridRichText Error : " + ex.Message);
return value;
}
return value;
}
}
}
然后在自定义的show对象中,添加引用using System.ComponentModel;
在某个属性的后面增加
[
EditorAttribute(typeof(PropertyGridRichText), typeof(System.Drawing.Design.UITypeEditor))
]
例如:
private string _mutiLineSample = "";
[
EditorAttribute(typeof(PropertyGridRichText), typeof(System.Drawing.Design.UITypeEditor))
]
{
get { return _mutiLineSample; }
set { _mutiLineSample = value; }
}
那么多行文本这个属性的效果就和之前的vs的textbox的text属性一样。可以显示多行。