Search code examples
c#wpfuser-controlslistboxitemssource

Listbox fails to show all of its items' content


I'm working on a C#/WPF program and created a user control consisting of two textboxes (and a grid).

There is a listbox in my main window. Its items source is set to a collection of my mentionend user controls. When I fill it and debug the program it holds 20 items and all items have text in it as I wanted it. But after the main window is loaded (and the listbox filled) it shows all items, but only nine of them have text boxes with text. The other ones have text boxes without any text.

What may be the reason for this?

Update: here is the code.

The user control:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="40" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <TextBox x:Name="NumberColumn" x:FieldModifier="public" Text="{Binding LineNumber}"
             Grid.Column="0" HorizontalAlignment="Right" />
    <TextBox x:Name="TextColumn" x:FieldModifier="public" Text="{Binding Text}"
             Grid.Column="1" HorizontalAlignment="Left" />            
</Grid>

The filling of the listbox:

string line;
Collection<CustomLine> lines = new Collection<CustomLine>();
StreamReader reader = new StreamReader(@"2008.sln");
while ((line = reader.ReadLine()) != null)
{
    CustomLine myLine = new CustomLine(line, lines.Count + 1);
    lines.Add(myLine);
}

this.leftListBox.ItemsSource = lines;

The XAML of the listbox:

<ListBox x:Name="leftListBox" Grid.Column="0" Margin="10"
             MouseDown="leftListBox_MouseDown" SelectionChanged="leftListBox_SelectionChanged">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <UserControl>
                    <local:CustomLine />
                </UserControl>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

If there another piece of code might be using, I may add it later, too.


Solution

  • Why did you wrap your CustomLine control in a UserControl tag?

    My best guess is that the UserControl is telling the ListBox that the items are an incorrect size, so the ListBox is only loading the items it thinks are visible. This is because the default behavior of a ListBox is to use UI Virtualization, so it only renders the controls that are visible, and scrolling the ListBox will re-use existing controls and replace the DataContext behind them instead of creating new controls.

    Try removing the UserControl in your ItemTemplate

    <ListBox.ItemTemplate>
        <DataTemplate>
            <local:CustomLine />
        </DataTemplate>
    </ListBox.ItemTemplate>