我有這樣的代碼:爲什麼我不能使用標籤保留文本框?
public static void AddDefaultTextFromTag(params TextBox[] textBoxes)
{
foreach (TextBox oTextBox in textBoxes)
{
bool isPasswordChar = oTextBox.UseSystemPasswordChar;
oTextBox.Enter += (sndr, evnt) =>
{
if (((TextBox)sndr).Text == ((TextBox)sndr).Tag.ToString())
{
((TextBox)sndr).Text = "";
((TextBox)sndr).UseSystemPasswordChar = isPasswordChar;
((TextBox)sndr).ForeColor = SystemColors.WindowText;
}
};
oTextBox.Leave += (sndr, evnt) =>
{
if (((TextBox)sndr).Text.Trim().Count() == 0)
{
((TextBox)sndr).UseSystemPasswordChar = false;
((TextBox)sndr).CharacterCasing = CharacterCasing.Normal;
((TextBox)sndr).Text = ((TextBox)sndr).Tag.ToString();
((TextBox)sndr).ForeColor = SystemColors.GrayText;
}
};
if (oTextBox.Text.Trim().Count() == 0)
{
oTextBox.UseSystemPasswordChar = false;
oTextBox.CharacterCasing = CharacterCasing.Normal;
oTextBox.Text = oTextBox.Tag.ToString();
oTextBox.ForeColor = SystemColors.GrayText;
}
}
}
但是當這種方法的參數TextBox.UseSystemPasswordChar
我輸入是真實的,它的TextBox.Text
屬性爲空,則TextBox
不能離開使用鍵盤上的Tab
按鈕,只有MouseClick
可以用來失去那個TextBox
的焦點。
這是怎麼發生的?我的代碼是在C#中,框架4,構建在VS2010 Pro中,項目在WinForms中。 我使用VS ToolBox中的TextBox。
請幫忙。提前致謝。
只是一個建議:爲什麼不創建兩個方法(Enter和Leave)並將它作爲事件處理程序附加到所有文本框,而不是使用每個自定義委託一? (我不認爲它們在這種情況下被重用,但我不確定)而不是複製代碼,您可以在所有這些代碼上運行Leave事件處理程序。 – Joey 2012-02-14 06:40:21
@Joey匿名方法是絕對重用的。在編譯期間,每個匿名方法都轉換爲該類的實例方法,並且該方法用於事件處理程序。所以不要擔心:) – 2012-02-14 07:07:17
啊,謝謝MD.Unicorn。然後可以忽略該部分,並使用最後一個減少代碼重複的建議;) – Joey 2012-02-14 12:54:50