您可以使用 DataSource 对组合框使用绑定。 ComboBox 还可以绑定到原始值(字符串/int/硬编码值)以外的其他事物。因此,您可以创建一个小类来表示您在 switch 语句中设置的值,然后使用 DisplayMember 来说明哪个属性应该在组合框中可见。
这样一个基本类的例子可以是
public class DataStructure
{
public double A { get; set; }
public int B { get; set; }
public string Title { get; set; }
}
由于您正在谈论用户向组合框动态添加值,因此您可以使用包含单独类的 BindingList,此 BindingList 可以是类中的受保护字段,当用户添加新的 DataStructure 时,您可以将新的 DataStructure 添加到该字段中,然后使用您添加的新值自动更新组合框。
ComboBox 的设置,可以在 Form_Load 中完成,也可以在 Form Constructor 中完成(在 InitializeComponent() 调用之后),如下所示:
// your form
public partial class Form1 : Form
{
// the property contains all the items that will be shown in the combobox
protected IList<DataStructure> dataItems = new BindingList<DataStructure>();
// a way to keep the selected reference that you do not always have to ask the combobox, gets updated on selection changed events
protected DataStructure selectedDataStructure = null;
public Form1()
{
InitializeComponent();
// create your default values here
dataItems.Add(new DataStructure { A = 0.5, B = 100, Title = "Some value" });
dataItems.Add(new DataStructure { A = 0.75, B = 100, Title = "More value" });
dataItems.Add(new DataStructure { A = 0.95, B = 100, Title = "Even more value" });
// assign the dataitems to the combobox datasource
comboBox1.DataSource = dataItems;
// Say what the combobox should show in the dropdown
comboBox1.DisplayMember = "Title";
// set it to list only, no typing
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
// register to the event that triggers each time the selection changes
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
}
// a method to add items to the dataItems (and automatically to the ComboBox thanks to the BindingContext)
private void Add(double a, int b, string title)
{
dataItems.Add(new DataStructure { A = a, B = b, Title = title });
}
// when the value changes, update the selectedDataStructure field
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox combo = sender as ComboBox;
if (combo == null)
{
return;
}
selectedDataStructure = combo.SelectedItem as DataStructure;
if (selectedDataStructure == null)
{
MessageBox.Show("You didn't select anything at the moment");
}
else
{
MessageBox.Show(string.Format("You currently selected {0} with A = {1:n2}, B = {2}", selectedDataStructure.Title, selectedDataStructure.A, selectedDataStructure.B));
}
}
// to add items on button click
private void AddComboBoxItemButton_Click(object sender, EventArgs e)
{
string title = textBox1.Text;
if (string.IsNullOrWhiteSpace(title))
{
MessageBox.Show("A title is required!");
return;
}
Random random = new Random();
double a = random.NextDouble();
int b = random.Next();
Add(a, b, title);
textBox1.Text = string.Empty;
}
}
像这样,您始终拥有选定的项目,您可以从选定的属性中请求值,并且您不必担心将 ComboBox 与当前可见的项目同步