views:

41

answers:

2

Hi, I created some buttons in Code like this.

if (infoLoader.categoriesLoaded)
        {
            sideBarButtons = new Button[infoLoader.categoriesLength];
            for (int i = 0; i < sideBarButtons.Length; i++)
            {
                sideBarButtons[i] = new Button();
                sideBarButtons[i].Content = infoLoader.categories[i].name;
                Canvas.SetLeft(sideBarButtons[i], 30);
                Canvas.SetTop(sideBarButtons[i], 110 + (40 * i));
                sideBarButtons[i].Click += new EventHandler(this.SideButton_Click);
                leftSideBar.Children.Add(sideBarButtons[i]);

            }
        }

With the Button Event handling function like this:

private void SideButton_Click(object sender, EventArgs e)
    {
        // Uhh
        Console.WriteLine("The Button has been clicked.");
        mainText.Text = infoLoader.games[0].id.ToString() + ", " + infoLoader.games[0].name + ": " + infoLoader.games[0].description;
        MainLaunchBtn.Content = "Launch " + infoLoader.games[0].name;
    }

And it's giving me the error:

Error 1 No overload for 'SideButton_Click' matches delegate 'System.EventHandler'

I'm kind of confused as to what I'm missing here, and any help would be appreciated. Thanks,

Andy

A: 

I think you want a method with this signature:

    private void SideButton_Click(object sender, RoutedEventArgs e)
    {

    }

and you can add the handler like this:

sideBarButtons[i].Click += SideButton_Click;
Bob
There's no need to change the method signature - a method which takes (object, EventArgs) can be used to construct a `RoutedEventHandler`. Admittedly you won't get the additional information from `RoutedEventArgs`, but it will compile and run just fine.
Jon Skeet
+2  A: 

The Button.Click event in WPF (inherited from ButtonBase) isn't of type EventHandler - it's RoutedEventHandler. I'm somewhat surprised about the exact error message you're getting, but you should be able to change your code to:

sideBarButtons[i].Click += new RoutedEventHandler(this.SideButton_Click);

or more simply:

sideBarButtons[i].Click += this.SideButton_Click;

Delegate variance will allow your existing method signature to be converted into a RoutedEventHandler even though the second parameter is of type EventArgs instead of RoutedEventArgs.

You should check that you've got the right using directives though - make sure you're genuinely creating WPF buttons instead of WinForms buttons.

Jon Skeet