设计时的 WinForms 组件属性
Posted
技术标签:
【中文标题】设计时的 WinForms 组件属性【英文标题】:WinForms component properties at Design time 【发布时间】:2017-09-16 03:26:20 【问题描述】:我尝试编写自己的组件来更改某些控件属性。我的想法是我将这个组件从工具箱放到表单中,在设计器的属性窗口中我可以选择应该使用哪个控件,就像这样:
我的代码是:
public class ShapeForm : Component
private int _shape;
public ShapeForm()
Shape = 20;
[TypeConverter(typeof(ControlTypeConverter))]
public Control TargetControl get; set;
[Browsable(false)] // don't show in the property grid
public List<Control> Controls get; private set;
public ContainerControl Target get; set; = null;
public override ISite Site
get return base.Site;
set
base.Site = value;
IDesignerHost host = value?.GetService(
typeof(IDesignerHost)) as IDesignerHost;
IComponent componentHost = host?.RootComponent;
if (componentHost is ContainerControl)
Target = componentHost as ContainerControl;
Controls = new List<Control>();
foreach (Control control in (componentHost as ContainerControl).Controls)
Controls.Add(control);
;
public class ControlTypeConverter : TypeConverter
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
// we only know how to convert from to a string
return typeof(Control) == destinationType;
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
Type destinationType)
if (typeof(string) == destinationType)
Control control = value as Control;
if (control != null)
return control;
return "(none)";
[
Category("Shaping"),
Description("Set corner shape radius"),
Browsable(true)
]
public int Shape
set
_shape = value;
//SetShaping();
get return _shape;
'
但我只得到一个元素,而不是像第一个屏幕截图那样以这种形式获得所有控件:
[]
【问题讨论】:
您已明确将其标记为不可浏览...如果我没记错,您还必须提供类型转换器。 不,它不会显示在下拉列表中。 【参考方案1】:使用此代码;
[Browsable(true)]
[Editor(typeof(TestDesignProperty), typeof(UITypeEditor))]
[DefaultValue(null)]
public string SelectedObject get; set;
public class TestDesignProperty : UITypeEditor
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
return UITypeEditorEditStyle.DropDown;
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
var edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
ListBox lb = new ListBox();
var form1 = (Form1) Activator.CreateInstance(typeof (Form1)); //Change with your form class
foreach (Control control in form1.Controls)
lb.Items.Add(control.Name);
if (value != null)
lb.SelectedItem = value;
edSvc.DropDownControl(lb);
value = (string)lb.SelectedItem;
return value;
【讨论】:
感谢您的回答。现在我有一个问题,Form 类是未知的。首先将这个组件放到我现在的表单中。 第二个问题:所有这些控件都显示为一个字符串对象,我没有一个“+”开头的视线,以折叠属性树。以上是关于设计时的 WinForms 组件属性的主要内容,如果未能解决你的问题,请参考以下文章
在设计时刷新属性网格,当只读集合在 .Net、Winforms 中更改时