错误:在使用 ItemsSource 之前,必须清空 Items 集合。
错误:在使用 ItemsSource 之前,必须清空 Items 集合。
我的xaml文件
xaml.cs文件
listBox1.Items.Clear(); for (int i = 0; i < tasks.Count(); i++) { List dataSource = new List(); 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”
有什么问题?
admin 更改状态以发布 2023年5月19日
你想要只创建一个列表并且只分配一次数据源!因此,在循环之前创建列表,并在循环之后分配数据源。
// 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. ListdataSource = new List (); // 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;