【问题标题】:How to bind Dictionary to ListBox in WinForms如何在 WinForms 中将字典绑定到 ListBox
【发布时间】:2010-12-03 04:20:42
【问题描述】:

可以将 Dictionary 绑定到 Listbox,在 Listbox 和成员属性之间保持同步吗?

【问题讨论】:

    标签: c# winforms dictionary data-binding listbox


    【解决方案1】:
    var choices = new Dictionary<string, string>(); 
    choices["A"] = "Arthur"; 
    choices["F"] = "Ford"; 
    choices["T"] = "Trillian"; 
    choices["Z"] = "Zaphod"; 
    listBox1.DataSource = new BindingSource(choices, null); 
    listBox1.DisplayMember = "Value"; 
    listBox1.ValueMember = "Key"; 
    

    (无耻地摘自我自己的博客:Bind a ComboBox to a generic Dictionary。)

    这意味着您可以使用 SelectedValue 来获取列表框中所选项目的相应字典键。

    【讨论】:

    • 那里真的需要BindingSource吗?
    • 是的,根据我的经验,它需要 BindingSource。
    • 是的,如果您事后修改基础字典,我不确定您是否会使其工作。字典不会像 BindingList 或 ObservableCollection 那样在更改时通知。
    • 其他人在创建新的 BindingSource(...) 时收到 ArgumentNull 异常??
    • 如果您的字典为空,您将得到一个空异常,您至少需要一项。
    【解决方案2】:
            label1.Text= listBox1.SelectedIndex.ToString();
    
            if ( listBox1.SelectedItem is KeyValuePair<int,DockStyle>)
            {
    
                var temp1 = (KeyValuePair<int, DockStyle>)listBox1.SelectedItem;
                label3.Text = temp1.Key.ToString();
                label4.Text = temp1.Value.ToString();
    
    
            }
    

    【讨论】:

    • 我知道这不是问题的匹配答案,但是当我需要在绑定后获取所选项目时,这很有帮助
    【解决方案3】:

    我认为您可以为此使用事件。每当 ListBox 发生变化时,eventHandler 方法都会从 Dictionary 中添加/删除相同的内容。

    【讨论】:

      猜你喜欢
      • 2012-06-15
      • 2011-02-10
      • 2016-04-18
      • 1970-01-01
      • 2021-10-03
      • 2016-02-18
      • 1970-01-01
      • 2013-05-26
      • 2010-12-21
      相关资源
      最近更新 更多