列表框项模板中的 WPF 扩展器是扩展的默认值
本文关键字:WPF 扩展器 扩展 默认值 列表 | 更新日期: 2023-09-27 18:36:16
我在ListBox ItemControl.ItemTemplate中有一个扩展器。 将数据绑定到列表框后,每个列表项上的所有扩展器都具有 IsExpanded = False。 我需要在手动将新列表项添加到列表框时将 IsExpanded 默认为 true。 我的 XAML 如下所示:
<ListBox
ScrollViewer.HorizontalScrollBarVisibility="Hidden"
ScrollViewer.CanContentScroll="False"
VirtualizingStackPanel.IsVirtualizing="False"
Grid.ColumnSpan="2"
HorizontalAlignment="Stretch"
Grid.Row="2"
Name="ArbitraryDataListbox"
ItemsSource="{Binding ElementName=CurrentArbitraryDataListControl, Path=CurrentJob.AdditionalData}">
<ListBox.Resources>
<Style TargetType="{x:Type Expander}">
<Setter Property="IsExpanded" Value="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderBrush" Value="Beige"/>
<Setter Property="Foreground" Value="#202020"/>
<Setter Property="Background" Value="Beige"/>
</Style>
</ListBox.Resources>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Expander Header="{Binding Path=Name}" Margin="0,8,0,0" IsExpanded="{Binding RelativeSource={RelativeSource self}, ElementName=ArbitraryDataListbox, Path=}">
<Controls:ArbitraryDataControl
Width="{Binding ElementName=ArbitraryDataListbox, Path=ActualWidth, Converter={StaticResource SubtractConverter}, ConverterParameter=10}"
CurrentArbitraryData="{Binding}"
CurrentJob="{Binding ElementName=CurrentArbitraryDataListControl, Path=CurrentJob}"/>
</Expander>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
我对 WPF 非常陌生,无法弄清楚如何在 IsExpanded 上设置绑定,因此手动打开新项目时确实如此。
感谢您提供的任何帮助!
如果我理解您的代码,现在您已展开列表框的选定项,其他项已折叠。 如果所选项目发生更改,则旧的选定项目将折叠,而新的选定项目将展开。
如果希望能够将项添加到集合,然后选择它,则应考虑使用 ListCollectionView。
ListCollectionView 环绕您的内部集合并公开"CurrentItem"。 您可以轻松地将此类绑定到ListBox,这将允许您在添加对象后调用ListCollectionView.MoveCurrentTo(object)以选择对象。