很抱歉发布了一个重复的问题。由于我的声誉,我无法在Hidden Id With ComboBox Items?
的评论中发布问题如何根据HiddenID从ComboBox中选择一个项目?
SQL示例:“从ComboList中选择displayValue,其中hiddenValue = 10"
为方便起见,我正在粘贴上述链接中的代码。
public class ComboBoxItem()
{
string displayValue;
string hiddenValue;
//Constructor
public ComboBoxItem (string d, string h)
{
displayValue = d;
hiddenValue = h;
}
//Accessor
public string HiddenValue
{
get
{
return hiddenValue;
}
}
//Override ToString method
public override string ToString()
{
return displayValue;
}
}
然后在你的代码中:
//Add item to ComboBox:
ComboBox.Items.Add(new ComboBoxItem("DisplayValue", "HiddenValue");
//Get hidden value of selected item:
string hValue = ((ComboBoxItem)ComboBox.SelectedItem).HiddenValue;
答案 0 :(得分:1)
您正在直接添加到组合框中控制项目。我所做的是创建一个List<>您所拥有的组合框项目自定义类。然后将组合框项目源设置为列表(几乎相同),但通过这样做,我可以明确地告诉组合框控件的哪个属性是SELECTED值与DISPLAY值(不能同时设置)。所以,我有以下......
List<ComboBoxItem> myList = new List<ComboBoxItem>();
myList.Add(new ComboBoxItem("Display Only", "I am Hidden"));
myList.Add(new ComboBoxItem("2nd line", "HV2"));
myList.Add(new ComboBoxItem("Show 3", "S3"));
ComboBox myCombo = new ComboBox();
myCombo.ItemsSource = myList;
myCombo.SelectedValuePath = "HiddenValue";
// specifically tell the combobox which "Hidden" value you want to set it to
myCombo.SelectedValue = "HV2";
//Get hidden value of selected item: should show "2nd line"
string showValue = myCombo.Text;
MessageBox.Show(showValue);