在C#的winform中,咱們都發現comboBox沒有一個能綁定內容的容器,而此外的控件都有一個tag屬性用來綁定信息,也沒有仔細查過,vs爲何這麼設計,不過有一種方法可以解決這個問題。
(1)咱們建立一個ComboBoxItem類:
public class
ComboBoxItem
{
private string _text = null;
private object _value = null;
public string Text { get { return this._text; } set { this._text = value; } }
public object Value { get { return this._value; } set { this._value = value; } }
public override string ToString()
{
return this._text;
}
}
(2)在添加的時間,咱們將這個類的列表添加到
comboBox的item屬性中:
private void Form1_Load(object sender, EventArgs e)
{
ComboBoxItem cbi1 = new ComboBoxItem();
cbi1.Text = "測試Test1";
cbi1.Value = "測試Value1";
comboBox1.Items.Add(cbi1);
ComboBoxItem cbi2 = new ComboBoxItem();
cbi2.Text = "測試Test2";
cbi2.Value = "測試Value2";
comboBox1.Items.Add(cbi2);
}
運行的時候咱們看到界面是這樣子的:
(3)在咱們使用的時候:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.Items != null && comboBox1.Items.Count > 0 && comboBox1.SelectedItem != null)
{
string text = ((ComboBoxItem)comboBox1.SelectedItem).Text;
object vlaue = ((ComboBoxItem)comboBox1.SelectedItem).Value;
}
}
其中test是表面要顯示的文檔,而vlaue則是咱們綁定的object的數據,給你們一個好玩的想法。我實現了一個下拉的菜單,其中comboBox1中綁定的數據都是winform頁面,甚至能夠控制各個窗體哦!很爽的哦!