重建用户控件时,用户控件自定义属性会丢失状态

时间:2011-04-13 04:20:33

标签: c# winforms user-controls properties custom-controls

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

[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”,这不是默认值。

如何在重建控件时阻止自定义属性丢失/更改其状态?

3 个答案:

答案 0 :(得分:4)

问题是DefaultValueAttribute只告诉设计器该属性的默认值是什么。它控制属性是否以粗体显示,以及当您右键单击属性并从上下文菜单中选择“重置”时,该值将重置为什么。

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

// set default visibility
this.removeButton.Visible = true;

否则,正如您所描述的,重建项目时将重置属性的值。它将在设计器的“属性”窗口中以粗体显示,因为它与默认值(在DefaultValueAttribute中指定)不匹配,但该属性不会更改值设置为。

答案 1 :(得分:2)

保持任何包含的控件属性不被重置(de)相关属性的序列化的简单方法是使用属性的私有支持字段,并且分配与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;

答案 2 :(得分:0)

旧帖子,但是它引导我找到了解决我的问题的方法。我确实具有相同的效果,即我的财产状态在重建时就丢失了。在我的情况下,该属性本身是一个类,它提供了一堆布尔值。

对我来说,解决方案是改变设计者对属性进行序列化的行为。

   [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public SomePropertyClass SomeProperty
{
    get { return _SomeProperty; }
    set { _SomeProperty = Value; }
}

通过使用DesignerSerializationVisibility.Content,您可以告诉设计者序列化属性类(SomePropertyClass中包含的布尔值)的内容,而不是属性本身。我猜另一种方法是使SomePropertyClass可序列化,但是上述方法实现起来更快。

也许对某人有帮助。 Sascha