我有一个简单的foreach语句,它创建一个usercontrol并将其添加到stackPanel控件(参见下面的代码)。产品只是一个int的列表。
foreach (int id in Products)
{
ItemControl itemControlProduct = new ItemControl (id );
this.StackPanelControl.Children.Add(itemControlProduct);
}
如果List有大约50个项目(产品),这可以正常工作,但一旦它结束,我的应用程序拒绝呈现。 (即没有例外,Windows任务管理员说程序运行正常,但没有窗口出现)
我该如何解决这个问题。我需要加载超过600件物品。 p.s我不想使用分页。我希望一次列出所有元素。
答案 0 :(得分:1)
StackPanel不是您正在寻找的父控件。使用ListView,它使用虚拟化面板(VirtualizingStackPanel),并且有许多好东西,例如用于选择事物的事件,更改外观而不改变背后的逻辑等。
“虚拟化”部分意味着在运行时只渲染有限数量的UI控件,无论您在容器中放置了多少项。
有很多方法可以做,下面的示例只是一个假设最少的样本:
<ListView ItemsSource="{Binding ...your binding to Products}">
<ListView.View>
<GridView>
<GridViewColumn Width="100">
<GridViewColumnHeader>
<TextBlock Text="Item"/>
</GridViewColumnHeader>
<GridViewColumn.CellTemplate>
<DataTemplate>
<ItemControl ItemId="{Binding Path=id}"/> <!-- this is for Product.id, you'll have to change it-->
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
答案 1 :(得分:1)
这不是一个直接的答案,但我强烈反对这种使用控件的“代码隐藏”方式。 WPF适用于数据绑定。创建一个视图模型,其中包含集合中的600个项目,让WPF进行艰苦的工作。
考虑使用ItemsControl
ItemsPanel
设置为VirtualizingStackPanel
。这将确保控件仅在可见时创建。将ItemsSource
属性绑定到您的收藏夹。
<ItemsControl ItemsSource="{Binding MyModel.MyCollection}">
<ItemsControl.ItemsPanel>
<VirtualizingStackPanel/>
</ItemsControl.ItemsPanel>
</ItemsControl>