Reputation: 45
I have an Expander inside a ListBox ItemControl.ItemTemplate. After data is bound to the ListBox, all Expanders on each ListItem has IsExpanded = False. I need to have IsExpanded default to true when a new ListItem is added to the ListBox manually. My XAML is as follows:
<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>
I'm VERY new to WPF and can't get my head around how to set a binding on IsExpanded so it is true when new items are manually open.
Thank you for any help you can provide!
Upvotes: 0
Views: 2926
Reputation: 11252
If I'm understanding your code, right now you have the SelectedItem of the ListBox expanded and the other items collapsed. If the selected item changes, the old selected item will collapse and the new selected item will expand.
If you want to be able to add an item to the collection and then select it, you should consider using a ListCollectionView.
ListCollectionView wraps around your inner collection and exposes a "CurrentItem". You can easily bind this class to your ListBox which will allow you to call ListCollectionView.MoveCurrentTo(object) to select the object after you add it.
Upvotes: 1