在我的小型WPF项目中,我有一个带有三个标签的TabControl
。每个标签上都有一个ListBox
。该项目记录了我们需要购买的杂货。 (不,这不是作业,而是我的妻子。)所以我有一个ShoppingListItem
列表,每个列表都有Name
和Needed
属性:true
当我们需要该项目时,以及我们购买后false
。
所以这三个标签是All,Bought和Needed。它们都应指向相同的ShoppingListItemCollection
(继承自ObservableCollection<ShoppingListItem>
)。但是Bought应该只显示Needed为false的项目,而Needed只显示Needed为true的项目。 (“全部”选项卡上的项目有复选框。)
这似乎 很难,但几个小时之后,我就没有更接近于解决这个问题了。看起来像CollectionView或CollectionViewSource是我需要的东西,但我无法发生任何事情;我检查并取消选中“全部”选项卡上的框,其他两个选项卡上的项目只是坐在那里盯着我。
有什么想法吗?
答案 0 :(得分:3)
您可以使用CollectionViewSource通过过滤器重复使用原始集合。
<Window.Resources>
<CollectionViewSource x:Key="NeededItems" Source="{Binding Items}" Filter="NeededCollectionViewSource_Filter" />
<CollectionViewSource x:Key="BoughtItems" Source="{Binding Items}" Filter="BoughtCollectionViewSource_Filter" />
</Window.Resources>
<TabControl>
<TabItem Header="All">
<ListBox DisplayMemberPath="Name" ItemsSource="{Binding Items}" />
</TabItem>
<TabItem Header="Bought">
<ListBox DisplayMemberPath="Name" ItemsSource="{Binding Source={StaticResource BoughtItems}}" />
</TabItem>
<TabItem Header="Needed">
<ListBox DisplayMemberPath="Name" ItemsSource="{Binding Source={StaticResource NeededItems}}" />
</TabItem>
</TabControl>
过滤器需要一些代码。
private void NeededCollectionViewSource_Filter(object sender, FilterEventArgs e)
{
e.Accepted = ((ShoppingListItem) e.Item).Needed;
}
private void BoughtCollectionViewSource_Filter(object sender, FilterEventArgs e)
{
e.Accepted = !((ShoppingListItem) e.Item).Needed;
}
答案 1 :(得分:0)
以下是一些想法: