重新构建用户控件时,用户控件自定义属性将失去状态

本文关键字:控件 用户 自定义属性 失去 状态 新构建 构建 | 更新日期: 2023-09-27 17:50:15

我有一个用户控件,自定义属性如下:

[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只告诉设计者属性的默认值是什么。它控制属性是否显示在粗体中,以及当您右键单击属性并从上下文菜单中选择"reset"时,该值将重置为什么。

没有做的是在运行时将属性设置为特定的值。为此,需要在用户控件的构造函数方法中放置代码。例如:

// 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。内容您告诉设计器序列化属性类的内容(SomePropertyClass中包含的布尔值),而不是属性本身。我想另一种方法是让SomePropertyClass序列化,但是上面的方法实现起来更快。

也许这对某人有帮助。Sascha