我正在使用数据绑定到 ICollectionView 的 WPF 列表框来显示可以过滤的项目列表。我正在使用 ListBox 上的上下文菜单对 Listbox 中的项目进行分组。为此,我在 Listbox 上定义了一个 groupstyle,它里面有一个扩展器。相同的代码如下。所有 xaml 代码都在 Generic.xaml 文件中,具有此 ListBox 的控件是在 CustomControls 库中定义的自定义控件。
<ListBox.GroupStyle>
<GroupStyle HidesIfEmpty="True">
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Margin" Value="0,0,0,5"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander Style="{StaticResource GroupBoxExpander}" IsExpanded="True"
BorderBrush="Black" BorderThickness="0,0,0,1" x:Name="expander">
<Expander.Header>
<DockPanel>
<TextBlock FontWeight="Bold" Text="{Binding Path=Name}"
Margin="5,0,0,0" Width="100"/>
</DockPanel>
</Expander.Header>
<Expander.Content>
<ItemsPresenter/>
</Expander.Content>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ListBox.GroupStyle>
使用 ICollectionView 的过滤器方法,我根据在与 ListBox 关联的文本框中输入的字符串过滤 Listbox 中的项目。因此,即使该组已折叠,如果已完成搜索的项目位于折叠的扩展器内,扩展器也会展开并且该项目在列表框中可见。但是,问题是当从文本框中删除搜索字符串时,扩展器应该回到它之前的状态,就像在这个状态下回到它的折叠状态一样。为此,我试图获取 exapnder 的 IsExpanded 属性,并根据其值,在搜索完成后将扩展器的状态设置为之前的状态。
我试图通过以下方式获取扩展器,但这里的问题是它只能在列表框的选择更改事件触发时发生:
FrameworkElement item = listbox.ItemContainerGenerator.ContainerFromItem(listbox.SelectedItem) as FrameworkElement; if (item != null) { GroupItem groupItem = item.GetVisualParent(); if (groupItem != null) { Expander expander = groupItem.Template.FindName("expander", groupItem) as Expander; if (expander != null) { expander.Collapsed += new RoutedEventHandler(expander_Collapsed); } } }
谁能告诉我这是否是正确的方法以及如何在文件旁边的代码中访问扩展器的 IsExpanded 属性,或者我可以尝试以不同的方式尝试吗?
索米。