【问题标题】:Error: Items collection must be empty before using ItemsSource错误:在使用 ItemsSource 之前,项目集合必须为空
【发布时间】:2012-03-04 07:33:56
【问题描述】:

我的 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 集合必须为空” 有什么问题?

【问题讨论】:

标签: c# visual-studio windows-phone-7


【解决方案1】:

您只想创建一次列表并只分配一次数据源!因此,创建列表before循环并分配数据源after循环

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

【讨论】:

    猜你喜欢
    • 2013-08-08
    • 1970-01-01
    • 2012-07-24
    • 2010-10-15
    • 1970-01-01
    • 2012-08-02
    • 2014-01-07
    • 1970-01-01
    • 2016-01-04
    相关资源
    最近更新 更多