Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ItemContainerGenerator.ContainerFromItem() returns null?

I'm having a bit of weird behavior that I can't seem to work out. When I iterate through the items in my ListBox.ItemsSource property, I can't seem to get the container? I'm expecting to see a ListBoxItem returned, but I only get null.

Any ideas?

Here's the bit of code I'm using:

this.lstResults.ItemsSource.ForEach(t =>
    {
        ListBoxItem lbi = this.lstResults.ItemContainerGenerator.ContainerFromItem(t) as ListBoxItem;

        if (lbi != null)
        {
            this.AddToolTip(lbi);
        }
    });

The ItemsSource is currently set to a Dictionary and does contain a number of KVPs.

like image 614
Sonny Boy Avatar asked Jul 15 '11 21:07

Sonny Boy


3 Answers

I found something that worked better for my case in this StackOverflow question:

Get row in datagrid

By putting in UpdateLayout and a ScrollIntoView calls before calling ContainerFromItem or ContainerFromIndex, you cause that part of the DataGrid to be realized which makes it possible for it return a value for ContainerFromItem/ContainerFromIndex:

dataGrid.UpdateLayout();
dataGrid.ScrollIntoView(dataGrid.Items[index]);
var row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index);

If you don't want the current location in the DataGrid to change, this probably isn't a good solution for you but if that's OK, it works without having to turn off virtualizing.

like image 100
Phred Menyhert Avatar answered Sep 28 '22 20:09

Phred Menyhert


Finally sorted out the problem... By adding VirtualizingStackPanel.IsVirtualizing="False" into my XAML, everything now works as expected.

On the downside, I miss out on all the performance benefitst of the virtualization, so I changed my load routing to async and added a "spinner" into my listbox while it loads...

like image 23
Sonny Boy Avatar answered Sep 28 '22 21:09

Sonny Boy


object viewItem = list.ItemContainerGenerator.ContainerFromItem(item);
if (viewItem == null)
{
    list.UpdateLayout();
    viewItem = list.ItemContainerGenerator.ContainerFromItem(item);
    Debug.Assert(viewItem != null, "list.ItemContainerGenerator.ContainerFromItem(item) is null, even after UpdateLayout");
}
like image 39
epox Avatar answered Sep 28 '22 21:09

epox