Get selected values from Listbox control RRS feed

  • Question

  • Hi All,

    I'm still new to SL so please bear with me.

    I have a ListBox being bound with some records from a DB.  Here's the xaml:

    <ListBox x:Name="lstClassSeries" SelectionMode="Multiple" DisplayMemberPath="Description" Grid.Row="11" Grid.Column="1"></ListBox>

    What I need is to get the values of the items that were selected and I can't seem to get it to work.  I've tried looping through the SelectedItems but there's no property for value or text.  I even tried to cast the item as a ListBoxItem but I get the following error:

    Unable to cast object of type 'UI.Silverlight.TransactionService.DTODropDown' to type 'System.Windows.Controls.ListBoxItem'.

    How can I get the values of the items selected?


    Monday, March 9, 2015 4:06 PM


  • You're using windows forms style techniques with xaml.

    This is a bad idea.

    You ought to learn MVVM.

    You probably don't think you want to learn it, but trust me on this one.

    Learn MVVM as soon as you can.


    There's a selecteditems collection.

    You have to cast   to listboxitem, it has a content property which you cast to whatever you put in there originally.

    Here's a snippet.

    I have a class foo, load a bunch of them in.  Do stuff. Work out what's selected in the click event of a button.

        public class foo
            public int id {get;set;}
            public string description  {get;set;}
        public partial class MainPage : UserControl
            public MainPage()
                lb.Items.Add(new ListBoxItem{Content=new foo{ id=1, description="a"}});
                lb.Items.Add(new ListBoxItem { Content = new foo { id = 2, description = "b" } });
                lb.Items.Add(new ListBoxItem { Content = new foo { id = 3, description = "c" } });
            private void Button_Click(object sender, RoutedEventArgs e)
                List<foo> selectedfoos = lb.SelectedItems.Cast<ListBoxItem>().Select(x=>x.Content as foo).ToList();

    Hope that helps.
    Recent Technet articles: Property List Editing; Dynamic XAML

    Monday, March 9, 2015 7:22 PM