I am new to Windows Phone,
I have one listbox with textblocks in it, I want to fetch all data from selected item in listbox.
Here is my code snippet:
.xaml file
<ListBox HorizontalAlignment="Left" Name="listbox1" ItemsSource="{Binding}" Margin="9,10,0,0" SelectionChanged="listBox1_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,5">
<Image HorizontalAlignment="Left" Height="100" Margin="0,15,0,0" VerticalAlignment="Top""/>
<TextBlock Text="{Binding AttractionName}" Foreground="Yellow" Margin="120,-110,0,0""/>
<TextBlock Text="Price:" Foreground="White" TextWrapping="Wrap" FontSize="30""/>
<TextBlock Text="£" Foreground="Green" TextWrapping="Wrap" FontSize="40" Margin="200,-50,12,0""/>
<TextBlock Text="{Binding price}" Foreground="Green" FontSize="40""/>
<Line X1="0" X2="420" Y1="10" Y2="10" Stroke="White" VerticalAlignment="Bottom"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
.cs file
void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs args)
{
Debug.WriteLine(" You selected " +listbox1.SelectedItem.ToString());
}
My console shows output this way: You selected Appname.Pagename.methodname
Class which is bound to ListBox
public class Attractions {
[JsonProperty("AttractionName")]
public string AttractionName { get; set; }
[JsonProperty("IphoneImage")]
public string IphoneImage { get; set; }
[JsonProperty("price")] public string price { get; set; }
}
There are few ways to do it:
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs args)
{
if (listBox1.SelectedIndex == -1) return;
Attractions first = listbox1.SelectedItem as Attractions ;
Attractions second = (Attractions)listBox1.Items[listBox1.SelectedIndex];
Attractions third = (sender as ListBox).SelectedItem as Attractions;
Attractions fourth = args.AddedItems[0] as Attractions;
Debug.WriteLine(" You selected " + first.AttractionName);
}
With SelectedItem (Index) you get an item that is Type of your ItemsSource Collection. Once you get the item you can do what you want with it.
Inside SelectionChange Event
put the following code
Attractions lbi = (sender as ListBox).SelectedItem as Attractions;
you can access the properties of the class using
lbi.price
write this code
This Can Help You
void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs args)
{
Debug.WriteLine(" You selected " +listBox1.Items[listBox1.SelectedIndex].ToString ());
}
来源:https://stackoverflow.com/questions/21480453/get-data-from-clicked-item-in-listbox