开发者

How to modify all ASP.NET controls to inherit from my special control?

TextBox, Label, Panel, ... all inherits from Control.

Is there a way to inherit from Control and make ASP.NET controls inherit from my new control?

For example, I have a control

public clas开发者_Go百科s SpecialControl : Control
{
    public string Something { get; set; }
}

Now I want all controls to inherit from it, so

<asp:TextBox ID="tb" runat="server" Something="hello" />

Would be valid.


You can't change the inheritance chain of the controls that are part of the BCL.


One thing you can do is to create an extension method as below.

<asp:TextBox id="tst" runat="server" Something="TestValue"></asp:TextBox> 

 public static string GetSomething(this WebControl value)
{
   return value.Attributes["Something"].ToString();
}

I only tested this for a TextBox control. May not be the ideal solution as it is not strongly typed but will work.


As Oded mentioned, you can't modify the inheritance chain of packaged controls.

What you can do is create wrappers for the packaged controls, and implement custom properties and methods in the wrappers. Here's a simple example of how to extend the TextBox:

[DefaultProperty("Text")]
[ToolboxData("<{0}:CustomTextBox runat=server></{0}:CustomTextBox>")]
public class CustomTextBox: System.Web.UI.WebControls.TextBox
{
    [Bindable(true)]
    [DefaultValue("")]
    public string Something
    {
        get
        {
            string something = (string)ViewState["Something"];
            return (something == null) ? String.Empty : something ;
        }
        set
        {
            ViewState["Something"] = value;
        }
    }

    protected override void RenderContents(HtmlTextWriter output)
    {
        output.Write(Text);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜