简体   繁体   English

覆盖 HyperLink.Text 属性无法正常工作

[英]Overriding HyperLink.Text property doesn't work correctly

I'm trying to work on a sub-class of System.Web.UI.WebControls.HyperLink in C# and I want to be able to specify a default text property that will replace the text value in certain conditions.我正在尝试处理System.Web.UI.WebControls.HyperLink中 System.Web.UI.WebControls.HyperLink 的子类,我希望能够指定一个默认文本属性,该属性将在某些条件下替换文本值。

public class MyHyperLink : HyperLink
{
    public string DefaultText { get; set; }

    public override string Text
    {
        get
        {
            return string.IsNullOrEmpty(base.Text)
                ? (this.DefaultText ?? string.Empty)
                : base.Text;
        }
    }
}

When I used this code my hyperlink rendered on the page but instead of <a>Default Text</a> I got <a text="Default Text"></a> .当我使用此代码时,我的超链接呈现在页面上,而不是<a>Default Text</a>我得到了<a text="Default Text"></a>

you don't need to override the Text property.您不需要覆盖 Text 属性。 You just need add a new string property and decorate that with the attribute PersistenceMode as showed below:您只需要添加一个新的字符串属性并使用属性 PersistenceMode 进行装饰,如下所示:

[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public string MyTextProperty{
    get
    {
       return ViewState["Text"] != null ? (string)ViewState["Text"] : string.Empty;
    }
    set
    {
        this.ViewState["Text"] = value;
    }
}

You're completely overriding the behaviour of the Text property though so it may well not render how it was designed to.您完全覆盖了 Text 属性的行为,因此它可能无法呈现其设计方式。 What you really want to do is override the Render method:您真正想要做的是覆盖 Render 方法:

protected override void Render(HtmlTextWriter writer)
{
    if (string.IsNullOrEmpty(base.Text))
    {
        Text = (this.DefaultText ?? string.Empty);
    }
    base.Render(writer);
}

This is cutting in just before the control renders to change the Text around.这是在控件呈现以更改 Text 之前插入的。 It is happening so late in the control lifecycle it isn't even going to be saved in ViewState to save bloating!它发生在控件生命周期的后期,它甚至不会保存在 ViewState 中以防止膨胀!

According to reflector, you did miss an attribute, and did not override the setter根据反射器,您确实错过了一个属性,并且没有覆盖设置器

public class MyHyperLink : HyperLink
{
    public string DefaultText { get; set; }

    [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
    public override string Text
    {
        get
        {
            return string.IsNullOrEmpty(base.Text) ? this.DefaultText : base.Text;
        }
        set
        {
            base.Text = value;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM