问题
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