[英]How do I add one event to all textboxes?
例如,我制作了這個物理計算器,在其中輸入了加速度和質量,它給了我力量。 現在我遇到了兩個問題:
1)當前事件是單擊鼠標,但是我認為在TextChanged事件中彈出答案會更好。 問題是,我有大約9個文本框,我不希望將相同的if語句添加到每個文本框事件中。 如何將大量代碼添加到每個文本框中,而不必將事件添加到每個文本框中?
2)我目前的處理方法是檢查每個“公式”是否每個文本框都為null。 這意味着我有一個相同的公式重復了3次,只是因為它的寫法不同。例如:F = ma可以寫為F / m = a,它用另一個if語句填充所有公式。 有什么方法可以使它比當前的方法更簡短? 因為現在我必須在每個if語句前面糾正這個問題:
else if (!String.IsNullOrEmpty(txtBoxAcc.Text) &&
String.IsNullOrEmpty(txtBoxFg.Text) &&
String.IsNullOrEmpty(txtBoxFn.Text) &&
String.IsNullOrEmpty(txtBoxF.Text) &&
String.IsNullOrEmpty(txtBoxFk.Text) &&
!String.IsNullOrEmpty(txtBoxMass.Text) &&
String.IsNullOrEmpty(txtBoxUk.Text) &&
String.IsNullOrEmpty(txtBoxVi.Text) &&
String.IsNullOrEmpty(txtBoxVf.Text) &&
String.IsNullOrEmpty(txtBoxTime.Text) &&
String.IsNullOrEmpty(txtBoxD.Text) &&
String.IsNullOrEmpty(txtBoxFnet.Text))
您需要在所有文本框中的TextChanged事件處理程序中注冊相同的方法,如下所示:
private void textBox_TextChanged(object sender, EventArgs e)
{
}
txtBoxFg.TextChanged += new System.EventHandler(this.textBox_TextChanged);
txtBoxFn.TextChanged += new System.EventHandler(this.textBox_TextChanged);
txtBoxF.TextChanged += new System.EventHandler(this.textBox_TextChanged);
txtBoxFk.TextChanged += new System.EventHandler(this.textBox_TextChanged);
txtBoxMass.TextChanged += new System.EventHandler(this.textBox_TextChanged);
txtBoxUk.TextChanged += new System.EventHandler(this.textBox_TextChanged);
txtBoxVi.TextChanged += new System.EventHandler(this.textBox_TextChanged);
txtBoxVf.TextChanged += new System.EventHandler(this.textBox_TextChanged);
txtBoxTime.TextChanged += new System.EventHandler(this.textBox_TextChanged);
txtBoxD.TextChanged += new System.EventHandler(this.textBox_TextChanged);
txtBoxFnet.TextChanged += new System.EventHandler(this.textBox_TextChanged);
謝謝
1)避免在代碼的不同位置處理類似事件。 由於您只處理文本框,因此在單個文本更改的事件處理程序中進行所有計算非常簡單。
只需將其鏈接到每個文本更改事件即可,而不用+ =
定義一個事件處理程序以使用多次:
EventHandler handler = (s, e) => {
var textBox = s as TextBox;
if (textBox == null)
return;
// handle event
};
獲取所有文本框的簡單方法,只是它不會在容器控件中搜索:
Controls
.OfType<TextBox>()
.ToList()
.ForEach(textBox => textBox.TextChanged += handler);
或更復雜的方法來獲取層次結構中的所有控件:
var visited = new HashSet<Control>();
// tricky way to have a recursive lambda
Action<Control, Action<Control>> visitRecursively = null;
visitRecursively = (control, visit) => {
// duplicate control test might be unnecessary
// but avoids infinite recursion or duplicate events
if (visited.Contains(control))
return;
visited.Add(control);
visit(control);
control
.Controls
.Cast<Control>()
.ToList()
.ForEach(subControl => visitRecursively(subControl, visit));
};
Action<Control> addMyHandler = control => {
TextBox textBox = control as TextBox;
if (textBox != null)
textBox.TextChanged += handler;
};
visitRecursively(this, addMyHandler);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.