Adding Objects to a Window or Page via a StackPanel

A StackPanel is one of the more common containers for objects. Unlike in Windows Forms, you can’t directly (programmatically) add controls to a page or a window; you need a layout mechanism like a Stack Panel. (That stinks vaguely of Java Swing GUI development, which requires a layout component for objects.)

The StackPanel control has two layouts: horizontal and vertical. Horizontal stacks items horizontally (like books on a shelf); vertical stacks items vertically, like a stack of dishes.

To add an object to a StackPanel (let’s call it _controls), you would simply write:

this._controls.Children.Add(someNewObject);

Similarly, if you want to find a control, you iterate through the collection of Children (which is a collection of UIElements).

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, WPF and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *