组合框的数据绑定

3

我正在按照以下方式向组合框添加项目:

   readonly Dictionary<string, string> _persons = new Dictionary<string, string>();
   ....
   //<no123, Adam>, <no234, Jason> etc..
   foreach (string key in _persons.Keys)
   {
        //Adding person code
        cmbPaidBy.Items.Add(key);                   
   }

我希望通过显示字典中的值(即名称)使组合框更易读。但是,我需要人员代码(如no123等)以便根据用户输入从数据库中获取数据。
正确的做法是什么?我该如何将值和键绑定到组合框项目中?

1
这是一个 WinForms 还是 WPF 的下拉框? - Andre Luus
4个回答

5

为您提供的DisplayMember和ValueMember属性:

cmbPaidBy.DataSource = new BindingSource(_persons, null); 
cmbPaidBy.DisplayMember = "Value"; 
cmbPaidBy.ValueMember = "Key"; 

更深入的信息在这里,以及在BindingSource类中。

BindingSource组件有许多用途。首先,它通过为Windows Forms控件和数据源之间提供货币管理、更改通知和其他服务,简化了将表单上的控件绑定到数据的过程。


哇!谢谢!有了那个,我使用 SelectedValue 来获取 valuemember。 - softwarematter

1

由于Dictionary<TKey, TValue>没有实现IList(或任何其他数据源接口),因此它不能用作绑定的数据源。您可以使用替代表示,例如DataTableList<KeyValuePair<TKey, TValue>>

在后一种情况下,您可以使用以下代码轻松绑定:

cmbPaidBy.ValueMember = "Key";
cmbPaidBy.DisplayMember = "Value";
cmbPaidBy.DataSource = _persons; // where persons is List<KeyValuePair<string,string>>

0

您可以在XAML中这样做:

<ComboBox ItemsSource="{Binding Persons}" DisplayMemberPath="Key" ValueMemberPath="Value" />

确保您可以绑定到集合(简单的字典不行,它不是可观察的集合)- 示例此处使用数据表...


0
在XAML中,将简单的字典(键值对)绑定到下拉框作为显示成员和值成员
<ComboBox Height="23" HorizontalAlignment="Left" SelectedItem="{Binding SelectedKeyValue}" SelectedValuePath="Value"  DisplayMemberPath="Key" Width="120"     x:Name="comboBox1" />

   <TextBox Height="23" HorizontalAlignment="Left" Name="textBox1" Width="120" Text="{Binding Path=SelectedValue, ElementName=comboBox1, Mode=TwoWay}"/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接