2013-06-20 66 views
1

我只是想創建一個按鈕列表。但每個按鈕應該做一些不同的事情。生成按鈕單擊事件的代理

它只是用於培訓。我是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()); 
      }); 
    } 

回答

1

我假設你想要的功能的陣列,並你想通過索引得到函數?

var clickActions = new RoutedEventHandler[] 
{ 
     (o, e) => 
      { 
       // index 0 
      }, 

     (o, e) => 
      { 
       // index 1 
      }, 

     (o, e) => 
      { 
       // index 2 
      }, 
}; 

for (int i = 0; i < clickActions.Length; i++) 
{ 
    Button acceptButton = new Button { Content = "Lösung" }; 
    acceptButton.Click += clickActions[i]; 
    someList.Items.Add(acceptButton); 
}  
+0

我只是試圖匿名委託分配給單擊(但我忘了把它包起來在RoutedEventHandler)。但你的解決方案也是可能的。謝謝:-) – Laokoon

+0

是的你說得對,正確的類型是RoutedEventHandler,但編譯器會接受相同簽名的lambda表達式。編輯答案更加正確。 – syclee

0

嗯,你可以做什麼。以下是簡單而簡單的。

for (int i = 0; i < answerList.Count; i++) 
{ 
    var acceptButton = new Button { Content = "Lösung" }; 
    acceptButton.Click += (s, e) => MessageBox.Show(i.ToString()); 
    someList.Items.Add(acceptButton); 
} 
0

你可以使用lambda表達式匿名方法:

for (int i = 0; i < answerList.Count; i++) 
{ 
    Button acceptButton = new Button { Content = "Lösung" }; 
    acceptButton.Click += (sender, args) => System.Windows.MessageBox.Show(i.toString()); 
    someList.Items.Add(acceptButton); 
}