[英]C# - Add custom property/attribute to new button
I try to developp an app for users to create a lot of computer's configuration, with OS / Language / etc ... 我尝试开发一个应用程序,供用户使用OS / Language / etc等创建大量计算机配置...
When he validate a configuration, I would like the choices to be stored in a custom attribute button 当他验证配置时,我希望将选择存储在自定义属性按钮中
private void VALIDATE_Click(object sender, EventArgs e)
{
string Computer = Text_Computer.Text;
if (myList.Any(str => str.Contains(Computer)))
{
MessageBox.Show(Computer+"Already Exist");
}
else
{
Button button = new Button();
button.Size = new System.Drawing.Size(195, 30);
button.Tag = Computer;
button.Name = Computer;
button.Text = Computer;
button.CustomOS = comboBox_OS.SelectedItem;
button.CustomLanguage = comboBox_Language.SelectedItem;
flowLayoutPanel3.Controls.Add(button);
myList.Add(Computer);
MessageBox.Show(Computer + "added");
}
In my GUI, if Users want to edit a configuration, he click on the new button representing the configuration and all choices are back, like : 在我的GUI中,如果用户要编辑配置,则他单击代表该配置的新按钮,然后所有选择都返回,例如:
comboBox_OS.SelectedItem = button.CustomOS;
comboBox_Language.SelectedItem = button.CustomLanguage;
Is that possible to create my custom attribute like button.CustomOS and button.CustomLanguage ? 是否可以创建我的自定义属性,例如button.CustomOS和button.CustomLanguage?
Regards 问候
It is possible and quite easy. 这是可能的,而且非常容易。 You just derive a new class from the original Button and declare two new Properties. 您只需从原始Button派生一个新类并声明两个新的Properties。 I included the code into a simple example. 我将代码包含在一个简单的示例中。
using System;
using System.Windows.Forms;
namespace StackOverflow
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void cbOS_SelectedIndexChanged(object sender, EventArgs e)
{
//Save selection.
ComboBox cb = (ComboBox)(sender);
btn1.CustomOS = cb.SelectedItem.ToString();
}
private void btnSelect_Click(object sender, EventArgs e)
{
//Restore selection on click.
MyButton btn = (MyButton)(sender);
cbOS.SelectedItem = btn.CustomOS;
}
//Declare a new class deriving from the original Button.
public class MyButton : Button
{
public String CustomOS { get; set; }
public String CustomLanguage { get; set; }
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.