[英]Display and Value Member in combobox c# wpf
我正在使用下面的代码将项目添加到组合框中,但是无法计算出如何在WPF中添加显示和值成员。 我尝试使用
DisplayMemberPath = MedName
和ValueMemberPath = MedID,但它仍仅使用MedName
任何帮助将不胜感激。
using (SqlConnection conn = new SqlConnection(connection))
{
try
{
SqlCommand sqlCmd = new SqlCommand("SELECT MedID, MedName FROM Medication", conn);
conn.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
comboBox_select_Item.Items.Add(sqlReader["MedName"].ToString());
}
sqlReader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Could not populate medication combobox from database.", ex.ToString());
}
}
我处理此类组合框的方式是通过ComboBoxPair类:
public class ComboBoxPair
{
public string Text { get; set; }
public int Index { get; set; }
public ComboBoxPair(string display, int idx)
{
Text = display;
Index = idx;
}
}
然后,我有一个只读的公共列表,例如:
public List<ComboBoxPair> MyPairs
{
get
{
return myPairs;
}
}
myPairs是一个私人名单,我用与您相同的方式填写:
myPairs.Add(new ComboBoxPair(sqlReader.GetString[1], sqlReader.GetInt32[0]));
现在在我的XAML中
<ComboBox IsReadOnly="False" ItemsSource="{Binding MyPairs}"
DisplayMemberPath="Text" SelectedValuePath="Index"
SelectedValue="{Binding MyPairValue, Mode=TwoWay}"
other values />
MyPairValue是应该保存所选MedID的int属性。
正确的方法是@JonathaWillcock的答案。
但是这里是最小的更改,以了解其工作原理:
XAML
<ComboBox DislayMemberPath="MedName" SelectedValuePath="MedID" ... />
在代码中,更改循环:
while (sqlReader.Read())
comboBox_select_Item.Items.Add(new {
MedName = sqlReader["MedName"].ToString(),
MedID = sqlReader["MedID"].ToString()
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.