【问题标题】:Windows Forms dynamic button custom action per button每个按钮的 Windows 窗体动态按钮自定义操作
【发布时间】:2019-05-12 18:23:08
【问题描述】:

我编写了一个函数 AddItem,它可以将项目添加到列表视图中。我还创建了一个函数来创建动态按钮。但是一旦我创建了一个动态按钮,我希望它在按下按钮时让 AddItem 函数工作。

我不知道如何解决这个问题,因为我对 C# 和 windows 窗体相对较新。

    private void AddButton(string Name, string Text, int Posx, int Posy, double Price, string ItemName)
    {
        // Create a Button object 
        Button NewButton = new Button();

        // Set Button properties
        NewButton.Height = 50;
        NewButton.Width = 120;
        NewButton.BackColor = Color.Gainsboro;
        NewButton.ForeColor = Color.Black;
        NewButton.Location = new Point(Posx, Posy);
        NewButton.Text = Text;
        NewButton.Name = Name;
        NewButton.Font = new Font("Microsoft Sans Serif", 12);

        // Add a Button Click Event handler
        NewButton.Click += new EventHandler(NewButton_Click);

        //Add to form ontop of panelButtonHamburgers
        panelButtonsHamburgers.Controls.Add(NewButton);

    }

    private void NewButton_Click(object sender, EventArgs e)
    {
        AddItem(Price, ItemName);
    }

正如您所见,AddButton 函数接受价格和商品名称,一旦单击按钮,我希望 additem 函数以相同的价格和商品名称运行。

谢谢!

【问题讨论】:

  • 您可以使用Button.Tag 属性来存储您需要的信息。然后,在事件处理程序中,将 sender 转换为 Control(或 Button)并检索 Tag 的内容(类型为 object,您可以在其中存储任何内容)。我建议你使用decimal 类型来表示Price(货币)。

标签: c# windows forms


【解决方案1】:

据我了解,您需要一个为每个动态按钮使用一些特定值的处理程序。您可以使用的方法很少。

  1. 使用 Tag 属性并以某种格式保存值

    newBut.Tag = $"{Price},{ItemName}";
    

    然后,在处理程序中

    //always check for null
    Button button = sender as Button;
    string data = button.Tag as string;
    //do staff with your data
    
  2. 创建字典,每次添加新按钮时将其作为键添加到字典,然后在处理程序中获取您的数据(但这是最糟糕的方法之一,因此请尽量避免使用它);

  3. 使用“命令”模式。创建一个特殊的类来执行你的操作。它应该是这样的

    class MyCommand
    {
            public double Price { get; set; }
            public string Name { get; set; }
            public ListView List { get; set; } //here is the list you want to add item to.
            public void Handle (object sender, EventArgs e)
            {
                    //Do your staff here
            }
    }
    

这有点棘手,但介绍了您将来可以使用的良好模式。

【讨论】:

    【解决方案2】:

    您可以将元组分配给按钮的Tag

    private void AddButton(string Name, string Text, int Posx, int Posy, double Price, string ItemName)
    {
        ...
    
        NewButton.Tag = (Price, ItemName);
    }
    

    然后您可以从事件中的sender 中获取该元组的值,这实际上是按钮。

    private void NewButton_Click(object sender, EventArgs e)
    {
        double price = (((double Price, string ItemName))((Button)sender).Tag).Price;
        string itemName = (((double Price, string ItemName))((Button)sender).Tag).ItemName;
    
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-04
      • 2019-12-15
      • 2013-06-05
      • 2011-11-15
      • 1970-01-01
      • 1970-01-01
      • 2012-11-08
      • 1970-01-01
      相关资源
      最近更新 更多