簡體   English   中英

如何創建自定義TextBox控件?

[英]How to create custom TextBox control?

我想在返回值之前在我的頁面上的每個TexBox控件上執行Trim()方法。 我不想為每個TexBox控件硬編碼相同的代碼,我想以更優雅的方式做到這一點。

我發現做了以下課程

namespace System.Web.UI.WebControls
{
    public partial class TrimmedTextBuox : TextBox
    {
        private string text;
        public override string Text
        {
            get { return string.IsNullOrEmpty(text) ? text : text.Trim(); }
            set { text = value; }
        }     
    }
}

但它失敗了,而debuggind編譯器沒有進入get{}set{}

在那之后,我創建了一個UserControl的項目,但必須從deriverd System.Web.UI.UserControl ,不System.Web.UI.WebControls.TextBox得到它的工作(有它指向一個例外)

那么,我該怎么做呢?

首先,您必須在.aspx頁面中注冊您的控件,如下所示:

<%@ Register TagPrefix="customControls" Namespace="WebApplication.Custom.Controls" Assembly="WebApplication"%>

然后你可以使用標記來調用它

<customControls:TrimmedTextBuox  ID="txtTrim" runat="server"/>

另外,您不必在自定義TextBox創建另一個“text”屬性。 相反,它可以這樣做:

namespace WebApplication.Custom.Controls
{
    public class TrimmedTextBuox : TextBox
    {
        public override string Text
        {
            get
            {                
                return base.Text;
            }
            set
            {
                if (!String.IsNullOrEmpty(value))
                    base.Text = value.Trim();
            }
        }
    }
}

這將在插入之前遞歸修剪所有文本框。

 public static void trimRecursive(Control root)
    {
      foreach (Control control in root.Controls)
      {
        if (control is TextBox)
        {
            var textbox = control as TextBox;
            textbox.Text = textbox.Text.Trim();
        }
        else
        {
            trimRecursive(control);
        }
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    trimRecursive(Page);
}

解決問題的簡單方法是使用new關鍵字隱藏基類的Text屬性。 示例代碼......

public class TrimmedTextBox : TextBox
{
    public new string Text
    {
        get
        {
             var t = (string) GetValue(TextProperty);
            return t != null ? t.Trim() : string.Empty;
        }
    }
}

有關具有屬性的新關鍵字如何工作的更多信息,請參閱此SO 問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM