Search code examples
c#listviewuwpdatatemplate

UWP - Changing ListViewItem Template on Add


I'm having an issue with my code when I try to add a ListViewItem via an observable collection and change it's DataTemplate.

            CurrentTicket.Add(new Item { itemID = selectedItem.itemID, price = price, name = selectedItem.name, taxID = selectedItem.taxID,modName = modNames });

        if(modNames.Count() != 0)
        {
            ListViewItem lvi = (ticketListBox).ContainerFromIndex(ticketListBox.Items.Count - 1) as ListViewItem;
            lvi.ContentTemplate = (DataTemplate)this.Resources["CurrentTicketModDataTemplate"];
        }

When I run this lvi returns null and the next line fails to execute. Any advice will be greatly appreciated.


Solution

  • The reason it was undefined is because the it makes more time to create the ListViewItem than it does to add to the observable collection. Solution is to wait until it is defined:

    ListViewItem lvi = ticketListview.ContainerFromItem(item) as ListViewItem;
                while(lvi == null)
                {
                    await Task.Delay(25);
                    lvi = ticketListview.ContainerFromItem(item) as ListViewItem;
                }