Dinindu Perera Dinindu Perera - 6 months ago 36
C# Question

Getting Listbox.SelectedItems

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?

<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" />


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)
//how do you get the selected data in the img, text, text2 on selection?


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;