Windows Phone 8:获取列表框的值项

时间:2014-02-17 16:17:43

标签: windows-phone-8

我有一个列表框。每个项目都有一个图像和标题(从我的列表绑定)。单击列表框中的项目时,如何获取该项目的标题值。

2 个答案:

答案 0 :(得分:7)

在ListBox中创建一个名为“SelectionChanged”的事件,并将该方法映射到XAML文件后面的代码中。在.cs文件中,从myListBox.SelectedItem获取值并将其强制转换为列表项类型。

EX:在XAML文件中

<ListBox x:Name="myListBox" ItemsSource="{Binding Items}"     
  SelectionChanged="myListBox_SelectionChanged">

在xaml.cs文件中:

private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var mySelectedItem = myListBox.SelectedItem as myObject;
}

我希望这会有所帮助。

答案 1 :(得分:2)

几乎没有类似的问题(firstsecond)。我会试着向你展示一个例子(很少扩展这个@KirtiSagar(if it helps accept his solution as it's the same method)所说的):

我们假设您的ItemClass看起来像这样:

public class ItemClass
{
    public Uri ImagePath { get; set; }
    public string Tile { get; set; }  // I used string as an example - it can be any class
}

然后将它绑定到ListBox,如下所示:

<ListBox Name="myList" Grid.Row="2">
   <ListBox.ItemTemplate>
      <DataTemplate>
          <StackPanel Orientation="Horizontal">
              <Image Source="{Binding ImagePath}"/>
              <TextBlock Text="{Binding Tile}"/>
          </StackPanel>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

这是一个非常简单的例子,但应该向您展示它的工作原理。

然后在我的Page和Constructor中,我需要添加我的Collection并订阅事件:

ObservableCollection<ItemClass> items = new ObservableCollection<ItemClass>();

public MainPage()
{
    InitializeComponent();

    myList.ItemsSource = items;
    myList.SelectionChanged += myList_SelectionChanged;
}

SelectinChanged事件可以通过多种方式用于您的目的。例如,您可以使用其SelectionChangedEventArgs属性。我将展示一些会产生相同结果的方法。我故意混淆了一些事情,以表明它是如何完成的。

private void myList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   if (myList.SelectedItem != null)
   {
       string myTile = ((sender as ListBox).SelectedItem as ItemClass).Tile;
       // you can also get your item like this - using EventArgs properties:
       string myTileToo = ((ItemClass)(e.AddedItems[0])).Tile;
   }
   // also you can get this by SelectedIndex and your Item Collection
   if ((sender as ListBox).SelectedIndex >= 0)
   {
       string myTileThree = items[myList.SelectedIndex].Tile;
   }
}

请注意,您的LisBox可以使用不同的SelectionModes,例如Multipe - 如果需要,您也可以尝试使用它(有属性SelectedItems和{ {1}} / AddedItemsRemovedItems)。

相关问题