user8094304
user8094304

Reputation:

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.

Upvotes: 0

Views: 87

Answers (2)

user8094304
user8094304

Reputation:

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

Upvotes: 1

J.B. Schubert
J.B. Schubert

Reputation: 31

You could try to set the DataTemplate and the DataContext.

Like this:

ListViewItem lvi = new ListViewItem();

lvi.DataTemplate = ticketListBox.DataTemplate;
lvi.DataContext = YourObservableCollection.Last();

Upvotes: 0

Related Questions