簡體   English   中英

生成按鈕單擊事件的委托

[英]generate a delegate for a Button-Click Event

我只想創建一個按鈕列表。 但是每個按鈕應該執行不同的操作。

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

我知道代表不是Func ...但是我不知道我該怎么做。

但這是行不通的。

您對我如何做這樣的事情有什么建議嗎?


編輯:解決方案

我是瞎子...沒想到要創建RoutedEventHandler :-)

private RoutedEventHandler anonymousClickFunction(int id) { 
        return new RoutedEventHandler(delegate(Object o, RoutedEventArgs e)
            {  
                System.Windows.Forms.MessageBox.Show(id.ToString()); 
            });
    }

我假設您想要一個函數數組,並且想要按索引獲取函數?

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);
}     

嗯,你能做什么。 以下,簡單明了。

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);
}

您可以將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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM