开发者

Button Handler in codebehind C# WPF

开发者 https://www.devze.com 2023-01-07 14:52 出处:网络
I created some buttons in Code like this. if (infoLoader.categoriesLoaded) { sideBarButtons = new Button[infoLoader.categoriesLength];

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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消