一种方法是将 ControlAdded 处理程序添加到面板,因此每次添加新文本框时,它都会自动为其添加 LostFocus 处理程序。下面一步一步来:
对于您的面板,您绑定了一个处理程序 ControlAdded 事件,类似于:
private void Panel1_ControlAdded(object sender, ControlEventArgs e)
{
var tb = e.Control as TextBox;
if (tb != null)
{
tb.LostFocus += new EventHandler(TextBox_LostFocus);
}
}
然后在 TextBox_LostFocus 你可以添加任何你想要的逻辑
void TextBox_LostFocus(object sender, EventArgs e)
{
var tb = sender as TextBox;
if (tb != null)
{
// modify tb.Text here, possibly like this...
tb.Text = String.Format("{0:C}", Decimal.Parse(tb.Text));
}
}
更新所有现有控件(未测试)
foreach (TextBox in panel1.Controls)
{
tb.LostFocus += new EventHandler(TextBox_LostFocus);
}