[英]WPF C# adding event handler programmatically
在我的代码中,我创建了一个TextBoxes数组:
namespace TCalc
{
public partial class MainWindow : Window
{
public TextBox[] pubAltArray;
public MainWindow()
{
InitializeComponent();
pubAltArray = new TextBox[10];
然后,我使用以下代码以编程方式创建TextBoxes:
private void generatePublishedTxtBox()
{
for (int i = 0; i < 10; i++)
{
TextBox pubAlt = new TextBox();
grid_profile.Children.Add(pubAlt);
pubAlt.SetValue(Grid.RowProperty, 1);
...
pubAltArray[i] = pubAlt;
}
}
当每个TextBox的内容更改时,我想运行一些例程:
private void doTheStuff(object sender, TextChangedEventArgs e)
{
...
}
所以我试图在新TextBox的定义期间添加事件处理程序,但是没有成功:
pubAlt.TextChanged += new System.EventHandler(doTheStuff());
要么
pubAlt.TextChanged += RoutedEventHandler(calculateCorAlts());
对我有什么提示吗?
尝试:
pubAlt.TextChanged += new TextChangedEventHandler(doTheStuff);
要么:
pubAlt.TextChanged += doTheStuff;
两条线都做相同的事情。 第二个只是第一行的简写,因为它使代码更易于阅读。
您正在使用()
调用方法。 更改您的代码,如下所示:
pubAlt.TextChanged += new System.EventHandler((s,e) => doTheStuff());
pubAlt.TextChanged += RoutedEventHandler((s,e) =>calculateCorAlts());
您的方法与要求的不匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.