【发布时间】:2011-06-11 10:44:15
【问题描述】:
我有一个问题。是否可以隐藏基本控件的某些元素和类别(对于自定义控件)。我只想显示我定义的属性。感谢您的宝贵时间。
【问题讨论】:
标签: c# custom-controls componentmodel
我有一个问题。是否可以隐藏基本控件的某些元素和类别(对于自定义控件)。我只想显示我定义的属性。感谢您的宝贵时间。
【问题讨论】:
标签: c# custom-controls componentmodel
隐藏属性并添加[Browsable(false)]。
例如:
[Browsable(false)]
public new SomeType SomeProperty {
get { return base.SomeProperty; }
set { base.SomeProperty = value; }
}
【讨论】:
您可以使用[Browsable(false)] 自定义属性来防止该属性出现在 WinForms 属性编辑器中:
[Browsable(false)]
public new PropertyType PropertyName
{
get { return base.PropertyName; }
set { base.PropertyName = value; }
}
但是,这将使该属性仍然有效,只是不会出现在表单设计器中。编译器会很乐意接受它。如果您希望该属性真正停止工作,请抛出异常:
[Browsable(false)]
public new PropertyType PropertyName
{
get { throw new InvalidOperationException("This property cannot be used with this control."); }
set { throw new InvalidOperationException("This property cannot be used with this control."); }
}
当然,编译器会仍然愉快地接受它,但它会在运行时抛出。然而,即便如此,客户端程序员仍然可以通过转换为基本类型来访问“原始”属性,即,而不是
myControl.PropertyName
他们会写
((BaseControlType) myControl).PropertyName
它仍然可以工作。对此您无能为力(只能从不同的基类派生)。
【讨论】:
Browsable 和 EditorBrowsable 都不会将其从 IntelliSense 中删除。那么 WinForms 是如何设法从 IntelliSense 中删除 Panel.KeyDown 的呢?