0

私はを使用して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?

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

リストボックスを使用する場合、このコードは問題ありません。

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