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());
});
}
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);
}
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);
}
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.