有时我们需要实现既能从UserControl中设定值又不想让用户直接编辑,就象一些Collection一样,只显示"(Collection)"串不可编辑又可以通过下拉或弹出窗体让用户选择。经过多次实现,发现属性项同时指定自定义Converter和Editor可以解决这个问题,后面附一些实现代码。
定义属性项:
[EditorAttribute(typeof(ContentEditor), typeof(UITypeEditor)),
TypeConverterAttribute(typeof(ConentConverter)),
DescriptionAttribute("Select item content")]
public ItemContent Content
{
get { return _itemContent; }
set { _itemContent = value; }
}
{
private string _type = "Type";
private string _c;
public string Type
{
get { return _type; }
}
public string Content
{
get { return _content; }
set { _content = value; }
}
}
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(ItemContent))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(System.String) &&
value is ItemContent)
{
return "(Collection)";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
{
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.DropDown;
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
IWindowsFormsEditorService service = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
SelectControl ctrl = new SelectControl();
if (value is ItemContent)
{
ctrl.Selected = (value as ItemContent).Content;
}
service.DropDownControl(ctrl);
(value as ItemContent).Content = ctrl.Selected;
return value;
}
}
最后将包含有ItemContent属性的类对象赋给PropertyGrid的SelectedObject即可。
原文地址:http://blog.51haipai.com/article.asp?id=4