我想获得动态添加的列表框中项目的当前索引。本质上,我的物品是一个HubTile,并且一次一个click事件添加焦点。这些具有争议的项目集合被保存在一个ObservableCollection中。这个可观察的连接绑定到显示项目的列表框。为了说明这一点,我有如下:如何获取动态添加到列表框的项目的索引
TabsPage.xaml
<ListBox x:Name="tileList" Grid.Row="0" Margin="12,0,12,0" toolkit:TiltEffect.IsTiltEnabled="True">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<toolkit:HubTile Title="{Binding TileName}" Margin="6"
Notification="{Binding Notification}"
DisplayNotification="{Binding DisplayNotification}"
Message="{Binding Message}"
GroupTag="{Binding GroupTag}"
Source="{Binding ImageUri}"
Tap="hubTile_Tap">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu x:Name="menu">
<toolkit:MenuItem Header="pin to start" Tap="MenuItem_Tap"/>
<toolkit:MenuItem Header="delete" Tap="deleteMenuItem_Tap"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</toolkit:HubTile>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
TabsPage.xaml.cs
ObservableCollection<TileItem> tileItems;
public TabsPage()
{
InitializeComponent();
CreateTileList(); //starts the list of HubTiles with a single main tile
}
private void CreateTileList()
{
tileItems = new ObservableCollection<TileItem>()
{
//TileItem is
new TileItem() { ImageUri = mainImage, Title = "main", /*Notification = "",*/ Message = "main", GroupTag = "MainGroup", TileName = "main" },
};
//Set the first tile item
this.tileList.ItemsSource = tileItems; //sets the tileList Listbox ItemsSource to the tileItems ObservableCollection
}
void addNew_Click(object sender, EventArgs e)
{
BitmapImage newTileImage = new BitmapImage();
var newItem = new TileItem() { ImageUri = newTileImage, Title = "new", /*Notification = "",*/ Message = "new HubTile", GroupTag = "TileGroup", TileName = "new" };
tileItems.Add(newItem); //update UI immediately and add to collection
}
private void hubTile_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
//how to get the current index of the tapped HubTile//
//var tap = (((sender as HubTile).Parent as ListBox).SelectedIndex); //NullReferenceException thrown
}
因此,HubTile项正确添加到用户界面,但在点击事件我不知道如何获取当前点击的HubTile项目的选定索引?