我使用的是ListBox
,数据是一个类:
private class Duration
{
public int Value { get; set; }
public string Label { get; set; }
}
我以这种方式绑定类:
var durations = new List<Duration>()
{
new Duration() { Value = 5, Label = "5 minutes" },
new Duration() { Value = 10, Label = "10 minutes" },
new Duration() { Value = 15, Label = "15 minutes" },
new Duration() { Value = 30, Label = "30 minutes" },
new Duration() { Value = 45, Label = "45 minutes" },
new Duration() { Value = 60, Label = "1 hour" },
new Duration() { Value = 90, Label = "1 hour and half" }
};
this.listTime.DataSource = durations;
this.listTime.DisplayMember = "Label";
this.listTime.ValueMember = "Value";
一切正常,标签显示。 当我去读取所选值时,我无法恢复所选项目的值。
我原本希望能够做到这一点:
int value = listTime.SelectedItems[0].Value;
或至少这个:
Duration value = listTime.SelectedItems[0];
但是这给了我错误,我做错了什么?如何在ListBox
上获取所选项目的价值的正确方法?
答案 0 :(得分:3)
if (listTime.SelectedIndex != -1)
{
var item = listTime.SelectedItem as Duration;
//or as suggested by 'Stu'
var item = (Duration)listTime.SelectedItem;
MessageBox.Show(item.Value.ToString());
}
答案 1 :(得分:1)
如果您使用Listbox,则此代码为Ok:
listTime.Items[0].Value