The WPF Expander represents a control with an expanded view where the contents of the expanded area can be expanded or collapsed. There are two ways to create an expander control in a WPF app. We can create an Expander control at design time using the <Expander> element of XAML. We can also use the Expander class in C# to create an expander at run-time.

The following XAML code sample shows how to create an Expander control in WPF.
<Expander Name="ExpanderControl" Header="Click to Expand" HorizontalAlignment="Left">
<TextBlock TextWrapping="Wrap" FontSize="14" FontWeight="Light" Foreground="Black">
This is an Expander control. Within this control, all contents will be wrapped.
At run-time, you may expand or collapse this control. Type more text here to be typed.
Jump around and hype.
</TextBlock>
</Expander>
The default view of an Expander control looks like this.

If you click on the header, the expanded view looks like this.

Most of the time, you would want the header of the Expander control to look different from the contents. This can be done by simply setting the font properties of the Expander control different from the contents.
This code sets the FontSize and FontWeight of the Expander control different from the contents of the Expander control.
<Window x:Class="ExpanderControlSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Expander Name="ExpanderControl"
Background="LavenderBlush"
HorizontalAlignment="Left"
Header="Click to Expand"
ExpandDirection="Down"
IsExpanded="False"
Width="200"
FontSize="20"
FontWeight="Bold"
Foreground="Green">
<TextBlock TextWrapping="Wrap">
This is an Expander control. Within this control, all contents will be wrapped.
At run-time, you may expand or collapse this control. Type more text here to be typed.
Jump around and hype.
</TextBlock>
</Expander>
</Grid>
</Window>
The new output looks like this. As you can see from this figure, the header of the Expander control is different from the contents.

How to create an Expander control dynamically?
The Expander class in WPF represents an Expander control.
This code snippet creates an Expander control at run-time.
private void CreateDynamicExpander()
{
Expander dynamicExpander = new Expander
{
Header = "Dynamic Expander",
HorizontalAlignment = HorizontalAlignment.Left,
Background = new SolidColorBrush(Colors.Lavender),
Width = 250,
IsExpanded = false,
Content = "This is a dynamic expander"
};
RootGrid.Children.Add(dynamicExpander);
}



Mahesh ChandPosted Dec 15, 2014, 11:45 PM
Thanks guys! Cheers!
Praveen KumarPosted Dec 15, 2014, 11:04 PM
It's too good!
Vithal WadjePosted Dec 15, 2014, 3:38 AM
good one..thanks for sharing