WPF - How to get only one expander expanded at any one time
-
20-09-2019 - |
Question
I've got a StackPanel with a group of expanders in, how do I set it so that only expander is expanded at any one time?
Cheers
AW
Solution
I didn't really want to do it like this as it required putting code (C#) in the class behind file for the window (I'm trying to avoid this completely by use of ViewModels etc).
Ideally I would have described this in XAML.
I hooked up every Expander 'Expanded' event I was interested in and did the following:
private void HandleExpanderExpanded(object sender, RoutedEventArgs e)
{
ExpandExculsively(sender as Expander);
}
private void ExpandExculsively(Expander expander)
{
foreach (var child in findPanel.Children)
{
if (child is Expander && child != expander)
((Expander)child).IsExpanded = false;
}
}
Cheers
AWC
OTHER TIPS
You can add a dependency property whose value is "the expander that is expanded," and then you can bind the "expanded" property to the expression "theExpandedProperty == this" using your favorite expression binding technique (type converter, etc).
Here is a more elaborate way to do it in WPF without any code behind:
<UserControl.Resources>
<ResourceDictionary>
...
<Style TargetType="{x:Type Expander}">
<Setter Property="IsExpanded" Value="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"/>
</Style>
</ResourceDictionary>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="{x:Null}" Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ScrollViewer VerticalAlignment="Top" HorizontalAlignment="Stretch" VerticalScrollBarVisibility="Auto" VerticalContentAlignment="Top" BorderThickness="0,0,0,0" Grid.RowSpan="1" Grid.Row="0">
<ListBox x:Name="OrdersListBox" BorderThickness="0" ItemContainerStyle="{StaticResource ShellThemeListBoxStyle}"
IsSynchronizedWithCurrentItem="True"
prism:RegionManager.RegionName="{x:Static uiCommon:RegionNames.WorkSheetsRegion}" Background="#00000000">
<ListBox.ItemTemplate>
<DataTemplate DataType="typeData:WorkSheetsDetialsViewModel">
<local:WorkSheetsDetialsView/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ScrollViewer>
...
</Grid>
<UserControl
x:Class="Module.ExcelDocumentManager.WorkSheets.WorkSheetsDetialsView"
...>
<Expander>
<Expander.Header>
<TextBlock Text="{Binding HeaderInfo}" RenderTransformOrigin=".5,.5">
</TextBlock>
</Expander.Header>
...
</Expander>
</UserControl>