c# - 如何在创建工具的同时创建工具事件?(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();
}
包含产品属性和添加到购物车按钮的表单单击此处查看它的外观
解决方案
我认为最好的解决方案是将对象与按钮相关联,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();
}
推荐阅读
- c# - 如何检查对象的任何子对象是否处于活动状态?
- react-native - 我很难在 react native 中滚动平面列表
- swift - 无法修复“编译器无法在合理时间内对该表达式进行类型检查;尝试将表达式分解为不同的子表达式”
- python - Pandas:如何在不循环的情况下使用 applymap/apply 函数对数据框进行争论
- javascript - 没有表列时如何传递参数 (GeomFromText('Polygon (( ? ?,))) node-maria
- excel - Xl.generateReport 文件位置不在服务器上创建 excel 报告
- python - 字节索引必须是整数或切片,而不是 str
- swift - 如何在类型上使用属性包装器抽象单例?
- r - ggplot 条形图在 Shiny 上无法正确显示
- vba - 在 VBA 中检查 pscp 传输的结果