【发布时间】:2023-03-27 14:29:01
【问题描述】:
我有一个ListView,里面装满了一些物品。这些项目有两个属性,ItemName 和 ItemGroup,我想按它们的第二个属性对它们进行分组。所以我写了这样的东西:
<Grid>
<Grid.Resources>
<Style x:Key="groupStyle" TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Expander IsExpanded="False" Header="{Binding Name}">
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<ListView x:Name="lv">
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ItemName}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
<ListView.GroupStyle>
<GroupStyle ContainerStyle="{StaticResource groupStyle}"/>
</ListView.GroupStyle>
</ListView>
</Grid>
在后面的代码中
// here, list is the collection of items with mentioned properties.
lv.ItemsSource = list;
var view = (CollectionView) CollectionViewSource.GetDefaultView(lv.ItemsSource);
if (view.GroupDescriptions != null)
{
view.GroupDescriptions.Clear();
view.GroupDescriptions.Add(new PropertyGroupDescription("ItemGroup"));
}
现在一切顺利。但问题是,有时我想在后面的代码中展开所有Expanders,我发现无法访问它们并将它们的IsExpanded 属性设置为true。我该怎么做?
编辑:这是我用来查找扩展器的方法,例如FindChildren<Expander>(lv) 但它总是返回一个空集合
public static IEnumerable<T> FindChildren<T>(DependencyObject obj) where T : DependencyObject
{
if (obj == null)
{
yield break;
}
int vt_count = obj is Visual ? VisualTreeHelper.GetChildrenCount(obj) : 0;
var children = vt_count > 0
? Enumerable.Range(0, vt_count).Select(n => VisualTreeHelper.GetChild(obj, n))
: LogicalTreeHelper.GetChildren(obj).OfType<DependencyObject>();
foreach (var child in children)
{
if (child is T)
{
yield return (T) child;
continue;
}
foreach (T descendant in FindChildren<T>(child))
yield return descendant;
}
}
【问题讨论】:
标签: c# wpf controltemplate expander