首页 > 解决方案 > 如何在创建工具的同时创建工具事件?(C#,Windows 窗体)

问题描述

作为我的作业要求,我必须在创建表单后立即创建与存储在 ProductManager 的数组中的产品数量一样多的按钮。按下按钮时,将打开另一个表单,显示产品的属性并允许将其添加到购物篮中。但是,由于这些按钮是最初创建的,因此我无法在它们的事件中按照我的意愿行事。比如我需要获取点击的按钮对应的是哪个产品,我需要以另一种形式展示这个产品的特性。这里出现了两个不同的问题:

1- 创建按钮后,我只需要使用它们的 Click 事件,但我无法访问它。

2- 我无法控制在显示产品详细信息的表单中单击按钮的产品。

加载表单时按钮自动出现的表单: 单击此处查看它的外观

private void Form2_Load(object sender, EventArgs e)
    {
        int buttonId = 0;
        int locationX = 2;
        int locationY = 2;
        for (int i = 0; i < productManager.getAll().Count; i++)
        {
            Button newButton = new Button();
            newButton.Image = Image.FromFile(productManager.getAll()[i].Path);
            newButton.Text =locationX.ToString();
            newButton.Size= new Size(180, 180);
            newButton.Location = new Point(locationX,locationY);
            locationX += 200;
            if (locationX > 805)
            {
                locationY += 200;
                locationX = 2;
            }
            this.Controls.Add(newButton);

            currentProduct = productManager.getAll()[i];
            newButton.Click += new EventHandler(button_Click);
        }
        
    }

我尝试使用的两个主题函数(事件):

 private void CurrentButton_Click(object sender, EventArgs e)
    {
        productDetailsWindow.Show();
    }

    protected void button_Click(object sender, EventArgs e)
    {
        Product product = sender as Product;
        productDetailsWindow.Show();
        
    }

包含产品属性和添加到购物车按钮的表单单击此处查看它的外观

标签: c#formswinformsobjectevents

解决方案


我认为最好的解决方案是将对象与按钮相关联,WinFroms 中的每个控件都有一个名为“TAG”的属性,在该属性中我将关联对象(在您的情况下是产品)并关联“单击”使用方法“NewButton_Click”的事件。因此,在窗口的 Load 事件中,它看起来像这样:

    private void Form2_Load(object sender, EventArgs e)
    {
        int buttonId = 0;
        int locationX = 2;
        int locationY = 2;
        for (int i = 0; i < productManager.getAll().Count; i++)
        {
            Button newButton = new Button();
            newButton.Image = Image.FromFile(productManager.getAll()[i].Path);
            newButton.Text = locationX.ToString();
            newButton.Size = new Size(180, 180);
            newButton.Location = new Point(locationX, locationY);
            locationX += 200;
            if (locationX > 805)
            {
                locationY += 200;
                locationX = 2;
            }
            this.Controls.Add(newButton);

            currentProduct = productManager.getAll()[i];
            newButton.Tag = currentProduct;
            newButton.Click += NewButton_Click;
        }

    }

在“NewButton_Click”方法中,“sender”参数与您按下的按钮相关联,因此我将“sender”参数转换为按钮,然后获得“Tag”属性,我知道它与如果它是产品中的对象,那么我想您的“productDetailsWindow”表单将创建一个产品类型属性,您可以将它们与之关联,您现在可以显示包含产品详细信息的窗口。“NewButtpm_Click”方法如下所示:

    private void NewButton_Click(object sender, EventArgs e)
    {
        var button = sender as Button;
        var product = button.Tag as Product;
        productDetailsWindow.Product = product;
        productDetailsWindow.Show();
    }

推荐阅读