Wednesday, March 24, 2010

WPF Fundamentals

WPF Fundamentals

WPF has some important new concepts that are beyond of what most .NET developers know from WinForms. But its very useful to understand these concepts before you start developing WPF applications.

XAML stands for Extensible Application Markup Language. Its a simple language based on XML that was invented for WPF to create and initialize user interface elements. The idea is similar to HTML.

Logical and Visual Tree
User interface elements in WPF have a hierachical relation. This is called the visual tree. A user interface element is composed of multiple parts. If you build a tree including all controls parts you have the logical tree.

The StackPanel is a simple and useful layout panel. It stacks its child elements below or beside each other, dependening on its orientation. This is very useful to create any kinds of lists. All WPF ItemsControls like ComboBox, ListBox or Menu use a StackPanel as their internal layout panel.


How do you like your coffee?
With milk
Latte machiato

Stack Items horizontally
A good example for a horizontal stack panel are the "OK" and "Cancel" buttons of a dialog window. Because the size of the text can change if the user changes the font-size or switches the language we should avoid fixed sized buttons. The stack panel aligns the two buttons depending on their desired size. If they need more space they will get it automatically. Never mess again with too small or too large buttons.


WPF Grid Layout Panel
The grid layout panel is the most powerful layout panel in WPF because its so flexible and universal in use. Thats the reason why Visual Studio adds a Grid layout control as root element by default to each Window or Page.
The grid layout defines a set of columns and rows. Each side of a control that has been added to the grid layout can now be bound to one of the row or colum with an optional margin.

Row:0 Col:0
Row:1 Col:1
Row:2 Col:2
Row:2 Col:2

Sizing rows and columns
The size of a row or a column can be defined in the following types
• Fixed size of logical units (wpf pixels)
• Auto takes as much space as needed by contained controls
• Star (*) takes as much space as possible, percentally split over all star columns. Like percentage in a HTML table except that the sum of all relative columns does not have to be 100