patrick
patrick

Reputation: 16999

ItemContainerGenerator returns null, why?

<ListBox BorderThickness="0" x:Name="PendingChatListBox" HorizontalContentAlignment="Stretch">
    <ListBox.ItemTemplate >
        <DataTemplate>
            <Button Height="40" Click="OpenChat_click" Content="{Binding BindsDirectlyToSource=True, Converter={StaticResource cPendingUnreadMessagesConverter}}"  HorizontalContentAlignment="Center" Background="Transparent" x:Name="OpenChatButton" Foreground="Blue"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
ObservableCollection<SideBarUnit> OpenChats = new ObservableCollection<SideBarUnit>();
this.PendingChatListBox.ItemsSource = OpenChats;


if (PendingChatListBox.Items.Count > 0)
{
    // WHY IS THIS OBJECT NULL?
    object obj = PendingChatListBox.ItemContainerGenerator.ContainerFromItem(PendingChatListBox.Items[0]); 
}

Upvotes: 0

Views: 916

Answers (1)

brunnerh
brunnerh

Reputation: 185578

Probably because of virtualization, items out of view have no container generated for them (if the items panel is virtualizing in nature; default for ListBoxes and the like).

Or if you assign a source and try to get the container in the same method the ListBox did not have the time to create it yet. The UI-thread must idle to do so.

Upvotes: 3

Related Questions