10

my xaml file

<ListBox Height="522" HorizontalAlignment="Left" Margin="20,162,0,0" Name="listBox1" VerticalAlignment="Top" Width="448" ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Text}" Foreground="#FFC8AB14" FontSize="36" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

xaml.cs file

       listBox1.Items.Clear();
       for (int i = 0; i < tasks.Count(); i++) {
            List<Taskonlistbox> dataSource = new List<Taskonlistbox>();
            dataSource.Add(new Taskonlistbox() {Text = "Blalalalala"} );
            this.listBox1.ItemsSource = dataSource; // visual stdio shows error here:
        }

Taskonlistbox:

public class Taskonlistbox
{
    public string Text { get; set; }
}

Error: "Items collection must be empty before using ItemsSource" whats a problem?

Alexander V.
  • 1,573
  • 3
  • 10
  • 12
  • 1
    This seems to related to http://stackoverflow.com/questions/683863/wpf-items-collection-must-be-empty-before-using-itemssource – Chriseyre2000 Feb 12 '12 at 18:26
  • Probably not the root error but you shouldn't set the ItemsSource inside the for-loop. – H H Feb 12 '12 at 18:28

1 Answers1

15

You want to create the list only once and assign the data source only once! Therefore, create the list before the loop and assign the data source after the loop

// Clear the listbox.
// If you never add items with listBox1.Items.Add(item); you can drop this statement.
listBox1.Items.Clear();

// Create the list once.
List<Taskonlistbox> dataSource = new List<Taskonlistbox>(); 

// Loop through the tasks and add items to the list.
for (int i = 0; i < tasks.Count(); i++) { 
    dataSource.Add(new Taskonlistbox {Text = "Blalalalala"} ); 
}

// Assign the list to the `ItemsSouce` of the listbox once.
this.listBox1.ItemsSource = dataSource;
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188