ASP.NET服务器控件中的默认值

5

我有一个关于默认值属性的问题。

当我将我的控件添加到设计模式下的页面时,默认值不起作用。这是我的代码:

[DefaultProperty("Text")]
[ToolboxData("<{0}:KHTLabel runat=server key=dfd></{0}:KHTLabel>")]
public class KHTLabel : Label ,IKHTBaseControl
{
    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("KHT")]
    [Localizable(true)]
    public string Key
    {
        get
        {
            String s = (String)ViewState["Key"];
            return ((s == null) ? String.Empty : s);
        }

        set
        {
            ViewState["Key"] = value;
        }
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {......

但是,在设计模式下,当我从工具箱中添加一个控件时,该键不存在

<cc1:KHTLabel ID="KHTLabel1" runat="server"></cc1:KHTLabel>
3个回答

4
很抱歉,[DefaultValue]属性并不是这样使用的。它允许Visual Studio设计器(特别是“属性”网格)确定默认显示什么,因此当值与默认值不同时,如何以粗体显示。

您需要在代码中拥有一个保持“KHT”作为默认值的值。在我的2008年博客文章中包含了一些相关细节。
以下代码比较基础,我无法验证它是否编译通过,但它应该能够让您了解如何“强制”将DefaultValueAttribute的值传递到ViewState中:
private string GetDefaultAttributeValueForProperty(string propertyName)
{
    var attributesForProperty = (from prop in typeof(KHTLabel).GetProperties()
                 where prop.Name == propertyName
                 select System.Attribute.GetCustomAttributes(prop)).First();
    var defaultValueAttribute = (from attr in attributesForProperty
                 where attr.GetType() == typeof(DefaultValueAttribute)
                 select ((DefaultValueAttribute)attr).Value).FirstOrDefault();

    return Convert.ToString(defaultValueAttribute);
}
public KHTLabel()
{
    ViewState["Key"] = GetDefaultAttributeValueForProperty("Key");
}

谢谢回复,它在设计模式下有效,但是否有任何方法可以将我的属性默认值添加到控件标记中,就像这样:<cc1:KHTLabel ID="KHTLabel1" Key="KHT" runat="server"></cc1:KHTLabel>? - MHF
@MHF - DefaultValue 属性不会为您执行此操作,也没有我知道的任何东西可以执行此操作。它不是用来这样做的,而且相当冗余,因为这将导致重复的值。 - Rob
@MHF - 我只是想知道,如果这个值是默认值,你为什么要在你的标记中看到它呢?=) - Rob
这样做更友好,方便其他使用此控件的开发人员 :) - MHF

2

DefaultValueAttribute 不用于设置属性的值。它被序列化器用来确定是否应该序列化该值。您需要在构造函数(或OnInit中)中设置属性的默认值。如果属性值与 DefaultValueAttribute 值匹配,使用 DefaultValueAttribute 会使序列化数据更小。


1

您可以通过在ToolboxDataAttribute中显式命名来获得您在第一个答案(<cc1:KHTLabel ID="KHTLabel1" runat="server" Key="KHT"></cc1:KHTLabel>)中提到的结果。为了使其成为实际的默认值,您仍然必须在属性的getter中返回该值。这将导致在您的类中重复三次相同的值。

顺便说一下,我不明白为什么您当前在ToolboxData中有key=dfd,而属性名称是Key,类型为字符串。

[DefaultProperty("Text")]
[ToolboxData("<{0}:KHTLabel runat=server Key=\"KHT\"></{0}:KHTLabel>")]
public class KHTLabel : Label//, IKHTBaseControl
{
    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("KHT")]
    [Localizable(true)]
    public string Key
    {
        get
        {
            var s = (String)ViewState["Key"];
            return (s ?? "KHT");
        }

        set { ViewState["Key"] = value; }
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {
        // TODO: Implement logic
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接