Skip to main content
 首页 » 编程设计

c#之如何在绑定(bind)后向 ItemsControl 添加更多项目

2024年02月06日12mq0036

在我的 C# Windows Phone 应用程序中,我创建了一个绑定(bind)以将字符串列表绑定(bind)到 ItemsControl。

// MyCollections is a List<string> 
 
<ItemsControl x:Name="ContentRoot" ItemsSource="{Binding MyCollections}"> 
    <ItemsControl.ItemTemplate> 
        <DataTemplate> 
            <TextBox Text="{Binding }" /> 
        </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

它有效。但我的问题是如何在绑定(bind)后向此 ItemsControl 添加我自己的项目(例如“单击以添加更多”)?

请您参考如下方法:

这个问题有两个答案:

  1. 使用 ObservableCollection 而不是 List,因为它会在向 UI 添加/删除项目时通知 UI。然后,您只需将新项目添加到 View 模型中的列表即可。

  2. 使用 CompositeCollection,这样您就可以在不修改实际集合的情况下拥有“附加”项目。

通常你会做 1,但因为你想要一个“点击添加更多”类型的选项,CompositeCollection 可能是要走的路。

既然您提到了 Windows Phone(但标记为 WPF),您可能想查看这篇文章以了解如何编写您自己的 CompositeCollection 对象:how to do a CompositeCollection in WP8?