[英]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.