我只是想創建一個按鈕列表。但每個按鈕應該做一些不同的事情。生成按鈕單擊事件的代理
它只是用於培訓。我是C#
的新手。
我現在所擁有的東西:
for (int i = 0; i < answerList.Count; i++)
{
Button acceptButton = new Button { Content = "Lösung" };
acceptButton.Click += anonymousClickFunction(i);
someList.Items.Add(acceptButton);
}
我想要生成Click-Function
這樣的:
private Func<Object, RoutedEventArgs> anonymousClickFunction(i) {
return delegate(Object o, RoutedEventArgs e)
{
System.Windows.Forms.MessageBox.Show(i.toString());
};
}
/// (as you might see i made a lot of JavaScript before ;-))
我知道委託是不是一個函數功能......但我不知道我必須在這裏做什麼。
但這不起作用。
你有什麼建議,我可以做這樣的事情嗎?
編輯:解
我是盲人......沒有想過建立一個RoutedEventHandler :-)
private RoutedEventHandler anonymousClickFunction(int id) {
return new RoutedEventHandler(delegate(Object o, RoutedEventArgs e)
{
System.Windows.Forms.MessageBox.Show(id.ToString());
});
}
我只是試圖匿名委託分配給單擊(但我忘了把它包起來在RoutedEventHandler)。但你的解決方案也是可能的。謝謝:-) – Laokoon
是的你說得對,正確的類型是RoutedEventHandler,但編譯器會接受相同簽名的lambda表達式。編輯答案更加正確。 – syclee