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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9251378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:33:03  来源:igfitidea点击:

Error: Items collection must be empty before using ItemsSource

c#visual-studiowindows-phone-7

提问by Alexander V.

my xaml file

我的 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 file

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

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

错误:“在使用 ItemsSource 之前,项目集合必须为空”有什么问题?

采纳答案by Olivier Jacot-Descombes

You want to create the list only once and assign the data source only once! Therefore, create the list beforethe loop and assign the data source afterthe 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;