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.
public class MyHyperLink : HyperLink
{
public string DefaultText { get; set; }
public override string Text
{
get
{
return string.IsNullOrE开发者_StackOverflow社区mpty(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>
.
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;
}
}
}
you don't need to override the Text property. You just need add a new string property and decorate that with the attribute PersistenceMode as showed below:
[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. What you really want to do is override the Render method:
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. It is happening so late in the control lifecycle it isn't even going to be saved in ViewState to save bloating!
精彩评论