2015-11-17 43 views
2

我正在尋找一種方法來綁定詞典到組合框如何將字典綁定到WinForms中的組合框?

這樣,當我更新字典的組合框時,它會自動反映到UI的變化。

現在我只能填充組合框,但是一旦我更新字典,沒有任何反映到組合框。

Dictionary<String,String> menuItems = new Dictionary<String,String>(){{"1","one"},{"2","two"}}; 
combo.DataSource = new BindingSource(menuItems, null); 
combo.DisplayMember = "Value"; 
combo.ValueMember = "Key"; 
menuItems.Add("ok", "success"); // combobox doesn't get updated 

== ==更新

目前我有致電combo.DataSource = new BindingSource(menuItems, null);刷新我的UI解決方法。

回答

4

Dictionary確實沒有屬性KeyValue。改爲使用List<KeyValuePair<string,string>>。另外,您需要撥打ResetBindings()才能正常工作。請看下圖:

private void Form1_Load(object sender, EventArgs e) 
    { 
     //menuItems = new Dictionary<String, String>() { { "1", "one" }, { "2", "two" } }; 
     menuItems = new List<KeyValuePair<string,string>>() { new KeyValuePair<string, string>("1","one"), new KeyValuePair<string, string>("2","two") }; 

     bs = new BindingSource(menuItems, null); 

     comboBox1.DataSource = bs; 
     comboBox1.DisplayMember = "Value"; 
     comboBox1.ValueMember = "Key"; 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     //menuItems.Add("3","three"); 
     menuItems.Add(new KeyValuePair<string, string>("3", "three")); 
     bs.ResetBindings(false); 
    } 

enter image description here

+0

你的解決方案是非常接近我的解決辦法。我一直在調用'combo.DataSource = new BindingSource(menuItems,null);'刷新我的UI。但我仍然喜歡我的,因爲使用字典給我一個簡單的方法來檢查重複密鑰,而不必調用#contains。 – TLJ

+0

好的,那麼...無論什麼適合你... – jsanalytics

+0

感謝您的幫助 – TLJ