WPF C# adding event handler programmatically

无人久伴 提交于 2021-01-28 23:11:08

问题


In my code I create an array of 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 :

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 :

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

So I tried to add event handler during the definition of new TextBox however without success :

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

or

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

Any hint for me?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/33004333/wpf-c-sharp-adding-event-handler-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!