绑定后如何向ItemsControl添加更多项目 [英] How to add more items to ItemsControl after binding
问题描述
在我的 C# windows 手机应用程序中,我创建了一个绑定来将字符串列表绑定到 ItemsControl
.
In my C# windows phone app, I create a binding to bind a list of string to ItemsControl
.
// MyCollections is a List<string>
<ItemsControl x:Name="ContentRoot" ItemsSource="{Binding MyCollections}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding }" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
它有效.但我的问题是如何在绑定后将我自己的项目(例如单击以添加更多")添加到此 ItemsControl
中?
It works. But My question is how can I add my own item (e.g. 'Click to add more') to this ItemsControl
after it is binded?
推荐答案
这个问题有两个答案:
使用
ObservableCollection
而不是List
,因为它会在添加/删除项目时通知 UI.然后你只需将你的新项目添加到视图模型的列表中.
Use an
ObservableCollection
instead of aList
, as it will notify the UI when items are added/removed from it. Then you just add your new item to the list in the view model.
使用 CompositeCollection
以便您可以拥有附加"项目而无需修改实际集合.
Use a CompositeCollection
so you can have the "additional" item without modifying the actual collection.
通常你会做 1,但因为你想要一个点击添加更多"类型的选项,CompositeCollection
可能是要走的路.
Normally you would do 1, but since you want a "Click to add more" type of option, CompositeCollection
is probably the way to go.
既然您提到了 windows phone(但标记了 WPF),您可能想查看这篇文章以了解如何编写自己的 CompositeCollection
对象:如何在 WP8 中做一个 CompositeCollection?
Since you metioned windows phone (but tagged WPF) you may want to look at this post for how to write your own CompositeCollection
object: how to do a CompositeCollection in WP8?
这篇关于绑定后如何向ItemsControl添加更多项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!