How to create Expander dynamically in WPF


The Expander class in WPF represents an Expander control.

This code snippet creates an Expander control at run-time. Here RootGrid is the Grid control on the window that is added to the window by default. By default, Grid control does not have a "Name". Set its Name property to "RootGrid".

private void CreateDynamicExpander()

{

    Expander dynamicExpander = new Expander();

    dynamicExpander.Header = "Dynamic Expander";

    dynamicExpander.HorizontalAlignment = HorizontalAlignment.Left;

    dynamicExpander.Background = new SolidColorBrush(Colors.Lavender);

    dynamicExpander.Width = 250;

    dynamicExpander.IsExpanded = false;

    dynamicExpander.Content = "This is a dynamic expander";

 

    RootGrid.Children.Add(dynamicExpander);

 

}