我有一个用户控件,其自定义属性如下。
[DefaultValue(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Description("Gets or sets whether the \"Remove\" button is visible.")]
public bool ShowRemoveButton
{
get
{
return this.removeButton.Visible;
}
set
{
this.removeButton.Visible = value;
}
}
该控件包含一个标准的按钮控件。这个属性用于显示或隐藏按钮。该用户控件建立在一个单独的项目组件中。我把它放在一个窗体上,我可以设置和取消设置上述属性,一切看起来都很正常。然而,当包含用户控件的项目被重建时,属性值翻转为 "false",这不是默认值。
如何防止自定义属性在控件重建时失去状态?
问题是 DefaultValueAttribute
只告诉 设计师 属性的默认值。它控制属性是否显示在 大胆当你右击属性并从上下文菜单中选择 "重置 "时,该值会被重置为什么。
它的内容 不 的作用是在运行时将属性设置为一个特定的值。要做到这一点,你需要在用户控件的构造方法中放置代码。比如说,你需要在用户控件的构造方法中放置代码。
// set default visibility
this.removeButton.Visible = true;
否则,正如你所描述的那样 当你重建项目时,属性的值会被重置。它将显示在 大胆 中的默认值,因为它与设计器的属性窗口中的默认值不匹配(如设计器中的 DefaultValueAttribute
),但该属性并不会改变值被设置为什么。
在相关属性的(去)序列化时,保持任何包含的控件的属性不被重置的一个简单方法是为属性使用一个私有的后盾字段,并且 赋予一个默认值,该值与 DefaultValue
属性的参数. 在这种情况下,这是 _showRemoveButton = true
下面的声明作业。
[DefaultValue(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Description("Gets or sets whether the \"Remove\" button is visible.")]
public bool ShowRemoveButton
{
get
{
return _showRemoveButton;
}
set
{
_showRemoveButton = value;
this.removeButton.Visible = value;
}
}
private bool _showRemoveButton = true;
老帖子,但它引导我找到了解决问题的方法。我有同样的效果,我的属性在重建时失去了状态。在我的例子中,属性本身是一个类,它提供了一堆布尔值。
对我来说,解决方案是改变设计者将属性序列化的行为。
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public SomePropertyClass SomeProperty
{
get { return _SomeProperty; }
set { _SomeProperty = Value; }
}
通过使用DesignerSerializationVisibility.Content,你告诉设计者序列化属性类的内容(我的布尔值包含在SomePropertyClass中),而不是属性本身。我想另一种方法是让SomePropertyClass可序列化,但上述方法实现起来更快。
也许这对某人有帮助.Sascha