确定哪个文本框已触发文本更改事件
我有许多通过代码动态创建的文本框。
我希望能够为所有文本框分配一个通用事件处理程序,以便更改文本,然后在处理程序中确定哪个文本框已触发事件。
我的代码是:
txtStringProperty.TextChanged += TextBoxValueChanged; private void TextBoxValueChanged(object sender, RoutedEventArgs e) { string propertyName = // I would like the name attribute of the textbox here }
如果您需要更多信息,请告诉我。
sender
参数包含触发事件的控件。 您可以将其强制转换为TextBox并从中获取name属性:
string propertyName = ((TextBox)sender).Name;
将object sender
(您触发事件的文本框)转换为TextBox
。
如果只有一个属性是你想要的那么写
string propertyName = ((TextBox)sender).Name;
但是当需要多个属性时,最好创建一个Textbox变量并使用它。
TextBox txtbox = (TextBox)sender;
然后你可以使用它的任何属性
string propertyName = txtbox.Name; MessageBox.Show(proptertyName); MessageBox.Show(txtbox.Content.ToString());
我的建议是在MSDN上查看基类层次结构,然后将控件转换为它并提取在其上定义的属性:
var name = ((ContentControl) sender).Name;
对于更通用的实现,这也是一种很好的做法,因为将其转换为“TextBox”意味着您只能将处理逻辑应用于该类型的控件。