从ListBox中单击的项目获取数据

时间:2014-01-31 12:47:29

标签: c# wpf xaml windows-phone-8 listbox

我是Windows Phone新手,

我有一个包含文本块的列表框,我想从列表框中的所选项目中获取所有数据。

这是我的代码段:

.xaml文件

 <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文件

    void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs args)
    {
        Debug.WriteLine(" You selected " +listbox1.SelectedItem.ToString());
    }

我的控制台以这种方式显示输出:You selected Appname.Pagename.methodname

绑定到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; } 
}

3 个答案:

答案 0 :(得分:3)

有几种方法可以做到:

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);
}

使用SelectedItem(索引),您将获得一个项目,即ItemsSource Collection的类型。一旦你得到了这个项目,你可以用它做你想做的事。

答案 1 :(得分:2)

SelectionChange Event内添加以下代码

Attractions  lbi = (sender as ListBox).SelectedItem as Attractions;

您可以使用

访问该类的属性
lbi.price

答案 2 :(得分:0)

编写此代码

这可以帮助你

void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs args)
    {
        Debug.WriteLine(" You selected " +listBox1.Items[listBox1.SelectedIndex].ToString ());
    }