【发布时间】:2011-03-20 06:30:15
【问题描述】:
我在过滤嵌套 xaml 模板中显示的分层数据时遇到问题。
我有一个ObservableCollection<Foo> Foos,我正在 XAML 中显示它。
假设 Foo 看起来像:
class Foo
{
public ObservableCollection<Bar> Bars;
}
class Bar
{
public ObservableCollection<Qux> Quxes;
}
我正在使用以下 xaml 显示 Foos:
<Grid>
<Grid.Resources>
<CollectionViewSource x:Key="MyCVS" Source="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListView}}, Path=DataContext.UnifiedSymbols}" Filter="MyCVS_Filter" />
<DataTemplate x:Key="NestedTabHeaderTemplate">
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
<DataTemplate x:Key="NestedTabContentTemplate">
<ListBox ItemsSource="{Binding Path=Quxes}" DisplayMemberPath="Name"/>
</DataTemplate>
<DataTemplate x:Key="TopLevelTabHeaderTemplate">
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
<DataTemplate x:Key="TopLevelTabContentTemplate">
<TabControl ItemsSource="{Binding Path=Bars}"
ItemTemplate="{StaticResource NestedTabHeaderTemplate}"
ContentTemplate="{StaticResource NestedTabContentTemplate}"
/>
</DataTemplate>
</Grid.Resources>
<TabControl ItemSource="{Binding correct binding for my control's collection of Foos}"
ItemTemplate="{StaticResource TopLevelTabHeaderTemplate}"
ContentTemplate="{StaticResource TopLevelTabContentTemplate}"
x:Name="tabControl"
/>
</Grid>
简单地说,有一个选项卡控件,每个 Foo 都有一个选项卡。每个 Foo 都是一个选项卡控件,每个 Bar 都包含在它自己的选项卡中。每个 Bar 都包含一个其 Quxes 的列表框。
或:
______ ______ ______
| Foo1 | Foo2 | Foo3 |
|______ ______ |
| Bar1 | Bar2 |______|
| | qux1 ||
| | qux2 ||
| | qux3 ||
----------------------
我还有一个文本框,我想用它来过滤这个细分。 当我在文本框中输入内容时,我想过滤 quxes,以便不包含文本的那些不可见。 理想情况下,Bar 选项卡如果没有可见的quxes,也将被隐藏, 和 Foo 选项卡在没有可见 Bars 时隐藏
我考虑了两种方法:
方法一,在适当的 CollectionViewSources 上重置 Filter 属性
在我的文本框的 TextChanged 事件中,我循环遍历我的 Foo 请求相应的(静态)TabControl 的 CollectionViewSource:
foreach(Foo foo in tabControl.Items)
{
var tabItem = tabControl.ItemContainerGenerator.ContainerFromItem(foo); // This is always of type TabItem
// How do I get the TabControl that will belong to each of Foo's Bar's?
}
方法二,将ListView的ItemSource声明为CollectionViewSource
我尝试通过 xaml 设置过滤器,方法是更改此行:
<ListBox ItemsSource="{Binding Path=Quxes}" DisplayMemberPath="Name">
到这里,
<CollectionViewSource x:Key="MyCVS" Source="?????" Filter="MyCVS_Filter" />
...
<ListBox ItemsSource="{Binding Source={StaticResource MyCVS}}" DisplayMemberPath="Name">
我已经尝试了很多我有“??????”的东西但我无法正确绑定到 ListBox 的数据上下文和适当的 Quxes 成员。我尝试的任何操作都不会导致显示 quxes,并且我在控制台上没有收到任何错误。即使我可以让这种方法发挥作用,我也不确定当搜索框中的文本发生变化时如何重新触发此过滤器。
任何建议或指导将不胜感激。
【问题讨论】:
标签: c# xaml binding filtering datatemplate