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

我知道代表不是 Func ......但我不知道我必须在这里做什么。

但这不起作用。

你有什么建议我可以做这样的事情吗?


编辑:解决方案

我是盲人......没想过创建一个 RoutedEventHandler :-)

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

3 回答 3

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);
}     
于 2013-06-20T08:50:00.220 回答
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);
}
于 2013-06-20T08:51:17.740 回答
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);
}
于 2013-06-20T08:51:51.487 回答