错误:在使用ItemsSource之前,Items集合必须为空

本文关键字:集合 Items 之前 ItemsSource 错误 | 更新日期: 2023-09-27 18:24:18

我的xaml文件

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

任务列表框:

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

错误:"在使用ItemsSource之前,Items集合必须为空"有什么问题?

错误:在使用ItemsSource之前,Items集合必须为空

您只想创建一次列表,只想分配一次数据源!因此,在循环之前创建列表,并在循环之后分配数据源

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