#427 – Changing Margins from Within Blend

You can adjust margins by entering values directly in XAML.  You can also change margins by clicking and dragging on elements on the design surface in Blend.

Below is a Grid with two buttons:

    <Grid ShowGridLines="True" Background="Beige" Margin="10">
        <-- row/col defs here -->
        <Button Grid.Row="0" Grid.Column="0" Content="Dance" Margin="5" VerticalAlignment="Center"/>
        <Button Grid.Row="1" Grid.Column="1" Content="Play Ukulele" Margin="5" HorizontalAlignment="Center"/>

Left-click on the Dance button on the design surface in Blend to see an indication of the margins.

Because the Dance button’s VerticalAlignment property is set to Center, it autosizes its height and the top/bottom margin values are not used.  The dashed lines above/below the button indicate that this distance is automatically set.

You can change the left or right margins by left-clicking on the left or right edges of the button and dragging.

You’ll see the margin value updated in the XAML.


#386 – Layout = Panels + FrameworkElements + Alignment/Margins/Padding

Layout in WPF is the process by which the location and size of all user interface elements is determined.

A user interface is composed of an outer Window or Page which contains a hierarchy of user interface elements.  The hierarchy can contain individual user interface elements or Panels, which in turn contain a collection of child FrameworkElements.

Panel is an abstract class that serves as a parent for specific layout panels, including Canvas, DockPanel, Grid, StackPanel and WrapPanel.

A panel will contain a collection of child FrameworkElement instances.  These can be individual controls that derive from FrameworkElement, directly or indirectly.  Because Panel is itself a child of the FrameworkElement class, a panel can contain other panels.

FrameworkElement child elements are position within a parent using properties related to alignment, margins and paddingThese properties include:

  • HorizontalAlignment, VerticalAlignment  and Margin  (from FrameworkElement)
  • HorizontalContentAlignment, VerticalContentAlignment and Padding  (from Control)