在WPF中使用ListBox时,如何以编程方式访问所选值

时间:2013-05-02 21:23:02

标签: c# wpf listbox

在我的代码中,我使用一个列表框来显示我正在创建的类中的对象。我想要的是能够单击列表框中的项目并以编程方式使用所选项目。这些项目来自字典,如下所示。

private Dictionary<Int32, MyClass> collection;

public Window1()
{
    ListBox1.SelectionChanged += new SelectionChangedEventHandler(ClickAnItem);
    ListBox1.ItemSource = collection;
}

现在,这一切都有效,ListBox会像我期望的那样显示我的集合,并且我会按照它应该触发事件,但我仍然坚持如何实际使用所选值。

private void ClickAnItem(object sender, RoutedEventArgs e)
{
    ListBox list = sender as ListBox;
    /** list has the Int32 and the MyClass object but I can't seem to 
     *  get them out of there programmatically
     */
}

我已经尝试将ListBox.SelectedItems转换为Dictionary类型的对象无济于事。

我没有运行它,但here is a question似乎相似。但是,如果可能的话,我想远离编辑XAML。我在运行时做的越多越好。

所以我的问题是,如何访问所选项目的'Int32'和'MyClass'?我过去曾经使用过C#但我现在只是跳回去了,这已经让我烦恼了一个多小时。

1 个答案:

答案 0 :(得分:2)

您需要从ListBox上的SelectedItem属性中获取值并将其强制转换为适当的类型。在您的情况下,这将是KeyValuePair<Int32, MyClass>,因为这是Dictionary

的组成部分

尝试一下:

private void ClickAnItem(object sender, RoutedEventArgs e)
{
   ListBox list = sender as ListBox;

   var selectedItem = listBox.SelectedItem as KeyValuePair<Int32, MyClass>;
}