重建用户控件时,用户控件自定义属性会丢失状态
我有一个自定义属性的用户控件,如下所示:
[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
属性的参数匹配的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;