2012-02-12 20 views
8

tập tin XAML của tôi nộpLỗi: Items bộ sưu tập phải có sản phẩm nào trước khi sử dụng ItemsSource

<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

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

Lỗi: "thấy bộ sưu tập phải trống trước khi sử dụng ItemsSource " có vấn đề gì?

+1

Điều này dường như liên quan đến http://stackoverflow.com/questions/683863/wpf-items-collection-must -be-empty-before-using-itemssource – Chriseyre2000

+0

Có lẽ không phải là lỗi gốc nhưng bạn không nên đặt ItemsSource bên trong vòng lặp for. –

Trả lời

13

Bạn chỉ muốn tạo danh sách một lần và chỉ gán nguồn dữ liệu một lần! Do đó, tạo danh sách trước vòng lặp và gán nguồn dữ liệu sau vòng lặp

// 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; 
+0

cảm ơn bạn rất nhiều! – tbsasa

Các vấn đề liên quan