重建用户控件时,用户控件自定义属性会丢失状态 [英] User Control custom properties lose state when user control is rebuilt

查看:76
本文介绍了重建用户控件时,用户控件自定义属性会丢失状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a user control with custom properties as follows:

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

The control contains a standard button control. This property is used to show or hide the button. The user control is built in a separate project assembly. I placed it on a form and I can set and unset the above property and everything appears to be working just fine. However, when the project containing the user control is rebuilt, the property value flips to "false", which is not the default.

如何防止自定义属性

推荐答案

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

The problem is that the DefaultValueAttribute only tells the designer what the default value is for the property. It controls whether the property is displayed in bold, and what the value gets reset to when you right-click on the property and choose "Reset" from the context menu.

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

What it doesn't do is set the property to a particular value at run-time. To do that, you'll need to place code in your user control's constructor method. For example:

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

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

Otherwise, as you've described, the value of the property will be reset when you rebuild the project. It will show up in bold in the Properties window of the designer, because it doesn't match the default (as specified in the DefaultValueAttribute), but that attribute doesn't change what the value is set to.

这篇关于重建用户控件时,用户控件自定义属性会丢失状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆