【问题标题】:C# custom control property: unable to set DefaultValue fieldC# 自定义控件属性:无法设置 DefaultValue 字段
【发布时间】:2013-01-09 12:49:55
【问题描述】:

我正在尝试设置自定义 C# 控件属性。

这是我的代码:

/* Cancel's button text */
[Category("ComboTouch"),
Description("Text to display in cancel button"),
DefaultValue("Cancel")]
public String ct_cancelButtonText { get; set; }

我在其他项目中使用自定义控件时可以获得该属性(如图所示);但配置参数DefaultValue 似乎不起作用。

有人可以帮我吗?非常感谢。

01/10/13 更新。非常感谢您的回答,您解决了我的问题。

我想分享一下我最终如何自动设置默认值:

  private String m_cancelButtonText="Cancel";

    /* Cancel's button text */
    [Category("ComboTouch"),
    Description("Text to display in cancel button"),
    DefaultValue("Cancel")]
    public String ct_cancelButtonText
    {
        get
        {
            return m_cancelButtonText;
        }
        set
        {
            m_cancelButtonText = value;
        }
    }

一个好奇:请检查“取消”文本的格式。如果我设置 DefaultValue 类型;它看起来像普通文本。但如果我不这样做,它看起来像粗体文本。我知道这很愚蠢;但我想知道为什么会这样。谢谢。

【问题讨论】:

  • Visual Studio 中属性选项卡中的默认值显示为普通文本,更改的属性显示为粗体。不知何故,VS 确定它不是默认设置的。

标签: c# default-value custom-properties


【解决方案1】:

documentation 中所述:

DefaultValueAttribute 不会导致成员使用属性值自动初始化。您必须在代码中设置初始值。

【讨论】:

  • 当你这样做的时候,确保你对 DefaultValue() 和字段初始化都使用一个(私有)常量。不要两次输入相同的内容。 :)
  • 非常感谢,您解决了我的问题。我用示例代码和另外一个问题编辑了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
  • 2016-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多