简体   繁体   English

WPF C#以编程方式添加事件处理程序

[英]WPF C# adding event handler programmatically

In my code I create an array of TextBoxes : 在我的代码中,我创建了一个TextBoxes数组:

namespace TCalc
{
    public partial class MainWindow : Window
    {
        public TextBox[] pubAltArray;

        public MainWindow()
        {
            InitializeComponent();

            pubAltArray = new TextBox[10];

Then I create the TextBoxes programmatically using the following code : 然后,我使用以下代码以编程方式创建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;
    }
}

Than I have some routine I want to run when the content of each TextBox changes : 当每个TextBox的内容更改时,我想运行一些例程:

private void doTheStuff(object sender, TextChangedEventArgs e)
{
...
} 

So I tried to add event handler during the definition of new TextBox however without success : 所以我试图在新TextBox的定义期间添加事件处理程序,但是没有成功:

pubAlt.TextChanged += new System.EventHandler(doTheStuff());

or 要么

pubAlt.TextChanged += RoutedEventHandler(calculateCorAlts());

Any hint for me? 对我有什么提示吗?

Try: 尝试:

pubAlt.TextChanged += new TextChangedEventHandler(doTheStuff);

or: 要么:

pubAlt.TextChanged += doTheStuff;

Both lines do the same thing. 两条线都做相同的事情。 The second one is just shorthand for the first line since it makes code easier to read. 第二个只是第一行的简写,因为它使代码更易于阅读。

You are invoking the method using () . 您正在使用()调用方法。 Change your code to be like this: 更改您的代码,如下所示:

pubAlt.TextChanged += new System.EventHandler((s,e) => doTheStuff());
pubAlt.TextChanged += RoutedEventHandler((s,e) =>calculateCorAlts());

Your method are not matching what it was asking for. 您的方法与要求的不匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM