0

So if I have a collection of variables which have been assigned data and binded to the listbox item template, how can I get the collection of data based on the selection of the listbox item?

<ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical" Height="500">
                    <Image Source="{Binding img }" Width="853" Height="480" VerticalAlignment="Top" Margin="0,10,8,0"/>
                    <StackPanel Width="370">
                        <TextBlock Text="{Binding text}" Foreground="#FFC8AB14" FontSize="28" />
                        <TextBlock Text="{Binding text2}" TextWrapping="Wrap" FontSize="24" />
                    </StackPanel>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>

C#:

 public class collection
    {
        public string text { get; set; }
        public string img { get; set; }
        public string text2 { get; set; }
    }

    private void ListBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
       ListBox1.SelectedItems
        //how do you get the selected data in the img, text, text2 on selection?
    }
H.B.
  • 166,899
  • 29
  • 327
  • 400
Dinindu Perera
  • 73
  • 1
  • 1
  • 12
  • Why are you binding collection of variables, instead group these variables in a class as properties and bind that class object collection would make things easy. – atp9 Aug 16 '16 at 13:26
  • do you have a list of collection you bound too as the itemsource of the list box? or your bound to 1 instance of collection? – Sam Aug 16 '16 at 13:30
  • the collection class is only the model, how do you populate your listbox? – Dark Templar Aug 16 '16 at 13:30

2 Answers2

2

Since you are binding your collection class in the ListBox, I presume that is done somewhere in the lying viewmodel on the back. The best approach then would always be to check for ListBox1.SelectedIndex and you can definitely bind it in your viewmodel too so you dont have to really access it on your codebehind. On that case you can definitely use a event to command or something like that to bind the SelectionChanged event back to the viewmodel.

If you do prefer to use the codebehind like the example you gave just check out ListBox1.SelectedIndex for single selection strategy and ListBox1.SelectedItems for multiple selection strategies.

Kindly have a look on this or this for more details on the context here. :)

Community
  • 1
  • 1
Swagata Prateek
  • 1,076
  • 7
  • 15
1

You need to cast your data. e.g. using LINQ

var items = ListBox1.SelectedItems.Cast<collection>();

Then you can iterate over them using foreach or the like, or access specific items, e.g.

var text1 = items.First().text;
H.B.
  • 166,899
  • 29
  • 327
  • 400