WPF Controls

  1. WPF controls
    1. Many common UI components like Button, Label, TextBox, Menu, and ListBox
    2. Add to XAML
      <Label x:Name="label1">Hello, WPF!</Label>
      
    3. Can also add programmatically
      Label myLabel = new Label();
      myLabel.Content = "Hello, WPF";
      grid1.Children.Add(myLabel);
      
  2. Control Layout
    1. Windows Forms: Set absolute (x,y) position
    2. WPF: Set relative position in its layout container
    3. Controls grow/shrink as window grows/shrinks
    4. Common layouts
      1. Grid - controls layed out in rows and columns
        Grid layout
      2. Canvas - controls positioned at explicit coordinates
        Canvas layout
      3. StackPanel - controls stacked left to right (Horizontal orientation) or top to bottom (Vertical orientation)
        StackPanel
      4. DockPanel - controls docked to left, right, top, bottom, or center
        DockPanel
      5. WrapPanel - controls stacked in one row (Horizontal orientation) or column (Vertical orientation)
        WrapPanel
    5. Best practices (source)
      1. Avoid fixed positions - use the Alignment properties in combination with Margin to position elements in a panel
      2. Avoid fixed sizes - set the Width and Height of elements to Auto whenever possible
      3. The Canvas panel is ideally just for vector graphics
      4. Use a StackPanel to layout dialog buttons
      5. Use a GridPanel to layout a static data entry form. Create an Auto sized column for the labels and a Star sized column for the TextBoxes
  3. Control properties
    1. Width, Height
      1. Device-independent unit (1/96th inch) measurement
      2. Can use other measurement units: px, in, cm, pt
      3. Auto to use minimum size around content
    2. MinWidth, MinHeight, MaxWidth, MaxHeight - define a range of acceptable values
    3. HorizontalAlignment (Left, Center, Right, or Stretch) and VerticalAlignment (Top, Center, Bottom, or Stretch)
      Various alignments
      From Christian Mosers' WPF Tutorial


    4. Padding (extra space inside the control) and Margin (extra space around the control) - L, T, R, B
      Padding and Margin