生成Button-Click事件的委托

时间:2013-06-20 08:41:47

标签: c# wpf delegates

我只是想创建一个按钮列表。但每个按钮应该做一些不同的事情。

仅用于培训。我是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()); 
            });
    }

3 个答案:

答案 0 :(得分: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);
}     

答案 1 :(得分: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);
}

答案 2 :(得分: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);
}