0

我正在使用 aListBox并且数据是一个类:

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什么?

4

2 回答 2

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());
}
于 2013-03-03T17:41:56.367 回答
1

如果您使用 Listbox,则此代码可以:

listTime.Items[0].Value
于 2013-03-03T17:37:05.143 回答