Laokoon
Laokoon

Reputation: 1301

generate a delegate for a Button-Click Event

I simply want to create a list of Buttons. But each button should do something different.

Its just for training. I'm new to C#.

what I have right now:

for (int i = 0; i < answerList.Count; i++)
{
     Button acceptButton = new Button { Content = "Lösung" };
     acceptButton.Click += anonymousClickFunction(i);
     someList.Items.Add(acceptButton);
}

I want to generate the Click-Function like this:

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

I know that a delegate is not a Func... but I don't know what I have to do here.

But this is not working.

Do you have any suggestions how i can do something like this?


EDIT: Solution

I was blind ... didn't thought about creating a RoutedEventHandler :-)

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

Upvotes: 1

Views: 3589

Answers (3)

syclee
syclee

Reputation: 697

I'm assuming you want an array of functions, and you want to get the function by index?

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

Upvotes: 1

Herm
Herm

Reputation: 2999

you can use lambda expressions for anonymous methods:

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

Upvotes: 0

DHN
DHN

Reputation: 4865

Hmm, what you could do. Is the following, plain and simple.

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

Upvotes: 0

Related Questions