问题描述
我的观点是这样的.我有一个 Observable 集合,其中包含放在列表中的对象.通过单击任何项目,我可以打开与该项目相关的扩展器.这是一个问题:我怎样才能当我打开另一个扩展器时折叠(关闭)先前打开的扩展器?我不想出现同时打开多个扩展器的情况.
My view works like this. I have an Observable Collection, which contains objects put on the list. By clicking on any item, I can open an expander related to that item. Here is the question: How can Icollapse (close) the previously opened expander when I open another one? I don't want to have a situation where multiple expanders are opened at the same time.
我的 WPF 代码如下所示:
My WPF code looks like this:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<controls:Pivot>
<controls:PivotItem>
<ListBox x:Name="PizzaList" SelectionChanged="PizzaList_SelectionChanged" IsSynchronizedWithCurrentItem="false" >
<ListBox.ItemTemplate>
<DataTemplate x:Name="template">
<toolkit:ExpanderView Header="{Binding Name}" x:Name="expander" Style="{StaticResource ExpanderViewStyle}">
<toolkit:ExpanderView.Items>
<!--first stack panel would contain all elements which would be showed
after clicking on listbox item-->
<StackPanel Margin="20,0,0,0" Orientation="Vertical">
<!-- here is content of expander-->
</StackPanel>
</toolkit:ExpanderView.Items>
<toolkit:ExpanderView.Expander>
<TextBlock Text="{Binding Name_of_ingredients}" Width="500"></TextBlock>
</toolkit:ExpanderView.Expander>
</toolkit:ExpanderView>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</controls:PivotItem>
</controls:Pivot>
</Grid>
如果我使用固定数据集,我可以拥有静态数量的扩展器,但是当扩展器位于数据模板中时,项目数量可能会发生变化.我不知道如何解决这个问题.
I could have a static number of expanders if I were working with a fixed dataset, but when the expander is in a data template, the number of items could change. I'm not sure how to solve this.
推荐答案
我认为这会有所帮助:
private void PizzaListSelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (var item in PizzaList.Items)
{
var listBoxItem =
PizzaList.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
var itemExpander = (Expander) GetExpander(listBoxItem);
if (itemExpander != null)
itemExpander.IsExpanded = false;
}
}
和搜索扩展器
private static DependencyObject GetExpander(DependencyObject container)
{
if (container is Expander) return container;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(container); i++)
{
var child = VisualTreeHelper.GetChild(container, i);
var result = GetExpander(child);
if (result != null)
{
return result;
}
}
return null;
}
在这个问题中找到控件的更多方法如何按名称或类型查找 WPF 控件?
More ways to find controls in this questionHow can I find WPF controls by name or type?
这篇关于当我们打开新的扩展器时,在“Datatemplate"中折叠打开的扩展器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!