Skip to content

2 Layouts

Overview

  • All controls in group help you with adjusting the layout of your application
  • You can think of it as a container for your controls, which helps you to arrange them in a specific way

How Size of Control is determined

  • The size of a control is determined by its Width and Height properties, which can be set to a specific value or to Auto
  • Width = 50 means control will be 50 pixels wide
  • Width = Auto means control will take as much space as it needs to display its content
  • Width = * means control will take all available space in the container, and if there are multiple controls with *, they will share the available space equally
  • You can also use MinWidth, MaxWidth, MinHeight, and MaxHeight properties to restrict the size of a control

Window

  • Title bar consule around 30-40 pixels of height so adjust your window height accordingly so all your controls are visible
  • Side border is around 8-10 pixels of width so adjust your window width accordingly so all your controls are visible
  • You can use WindowStyle property to hide title bar and border of window
  • Or Can set WindowStyle="None" and ResizeMode="NoResize" to make your window borderless and non-resizable

Grid

  • This is sample code to create a Grid with 4 rows and 2 columns
  • You can use Grid.Row and Grid.Column properties to set your control to a specific position
  • You can also create another Grid inside a Grid cell to create complex layouts
  • Additionally use can use Grid.RowSpan and Grid.ColumnSpan properties to make your control span across multiple rows or columns without creating extra rows or columns in your grid

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <TextBlock  
        Grid.Row="0" 
        Grid.Column="0"  
        Name="NameTextBlock" 
        Text="Vivek Patel" 
        FontSize="50" 
        HorizontalAlignment="Left" 
        VerticalAlignment="Center"/>
</Grid>
| Property | Description | |----------|-------------| | Grid.Row | Sets the row index of the control | | Grid.Column | Sets the column index of the control | | Grid.RowSpan | Sets the number of rows the control should span | | Grid.ColumnSpan | Sets the number of columns the control should span |

Stack Panel

  • Arranges all elements in single line vertically/horizontally
  • Perfect when you need single direction layouts like list
    <StackPanel Orientation="Vertical" Margin="10">
        <Button Content="Button 1" Height="40"/>
        <Button Content="Button 2" Height="40"/>
        <Button Content="Button 3" Height="40"/>
    </StackPanel>
    
    <StackPanel Orientation="Horizontal" Margin="10">
        <Button Content="Yes" Width="75" Margin="5"/>
        <Button Content="No" Width="75" Margin="5"/>
        <Button Content="Cancel" Width="75" Margin="5"/>
    </StackPanel>
    
  • You can also use with with other controls like
  • button with logo & Text
  • Lable with logo & Text
    <Button>
        <StackPanel Orientation="Horizontal">
            <Image Source="save.png" Width="16" Height="16"/>
            <TextBlock Text="Save"/>
        </StackPanel>
    </Button>
    

Dock Panel

  • DockPanel allows you to dock your controls to the top, bottom, left or right of the container
  • You can use DockPanel.Dock property to set your control to a specific position
  • If no dock position is specified, the control will assume the default position of Left
  • You can use it for setting up a header, footer, sidebar, or any other layout where you want to dock controls to the edges of the container

<DockPanel>
    <!-- Top -->
    <TextBlock Text="Header"
                Background="LightBlue"
                DockPanel.Dock="Top"
                Padding="10"/>
    <!-- Left -->
    <Button Content="Menu"
            Width="80"
            DockPanel.Dock="Left"/>
    <!-- Remaining space -->
    <TextBox Text="Main Content Area"
                AcceptsReturn="True"/>
</DockPanel>
+-------------------------+
| Header                  |
+-----+-------------------+
|Menu |                   |
|     | Main Content Area |
|     |                   |
+-----+-------------------+
<DockPanel>

    <Border Background="LightBlue"
            Height="40"
            DockPanel.Dock="Top"/>

    <Border Background="LightGreen"
            Height="40"
            DockPanel.Dock="Bottom"/>

    <Border Background="LightCoral"
            Width="80"
            DockPanel.Dock="Left"/>

    <Border Background="LightYellow"
            Width="80"
            DockPanel.Dock="Right"/>

    <Border Background="White"/>

</DockPanel>
+-----------------------+
|        TOP            |
+----+-------------+----+
|    |             |    |
|LEFT|   CENTER    |RIGHT
|    |             |    |
+----+-------------+----+
|       BOTTOM          |
+-----------------------+

Property Description
LastChildFill occupy all remaining space if true

Canvas

  • It's simplest layout control in WPF, Unlike Grid and StackPanel, Canvas does not have any layout logic, it just places the controls at the specified position
  • You can use Canvas.Left, Canvas.Top, Canvas.Right and Canvas.Bottom properties to set your control to a specific position
  • You can use it for drawing or visualization scenarios where you need to place controls at specific coordinates
  • Here is sample code to place button on canvas and move it on click of button

<Window x:Class="CanvasDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Canvas Demo" Height="300" Width="400">

    <Canvas Name="MyCanvas" Background="LightGray">
        <Button Name="MyButton" Content="Move Me"
                Width="100" Height="30"
                Canvas.Left="50" Canvas.Top="50"
                Click="MyButton_Click"/>
    </Canvas>
</Window>
//Code behind for window with canvas
public partial class MainWindow : Window
{
    private double _x = 50;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void MyButton_Click(object sender, RoutedEventArgs e)
    {
        _x += 20;

        Canvas.SetLeft(MyButton, _x);
    }
}
//Sample code to add rectangle on canvas via code behind
 Rectangle rect = new Rectangle
{
    Width = 100,
    Height = 50,
    Fill = Brushes.LightGreen
};

Canvas.SetLeft(rect, 100);
Canvas.SetTop(rect, 100);

MyCanvas.Children.Add(rect);

//Sample code to add circle on canvas via code behind
Ellipse circle = new Ellipse
{
    Width = 50,
    Height = 50,
    Fill = Brushes.LightBlue
};
Canvas.SetLeft(circle, 200);
Canvas.SetTop(circle, 150);
MyCanvas.Children.Add(circle);

Property Description
Canvas.Left Sets the distance between the left edge
Canvas.Top Sets the distance between the top edge
Canvas.Right Sets the distance between the right edge
Canvas.Bottom Sets the distance between the bottom edge
Canvas.ZIndex Set Zvalue of control, higher will be on top
Method Description
Canvas.SetLeft(element, value) Set X position
Canvas.SetTop(element, value) Set Y position
Canvas.GetLeft(element) Read X position
Canvas.GetTop(element) Read Y position
Canvas.Children.Add(element) Add a control or shape

Content Control

  • It's placeholder that can display a single piece of content which you can swap out at runtime, such as a button, text, image, or entire layout.
  • You can use it to create dynamic UIs where the content changes based on user interaction or application state like swapping between different views or pages in a single window.
  • Perfect for sidebar navigation with different views
  • Content Control is base class for many other controls like Button, Label, ListBox, ComboBox, etc. which can hold a single piece of content.
    <ContentControl Name="MainContent"/>
    
    //Code behind to set content of ContentControl
    MainContent.Content = new Button { Content = "Click Me" };
    
    Content control with navigation buttons
    Views
    ├─ ClientsView.xaml
    ├─ ProjectsView.xaml
    └─ ReportsView.xaml
    
    +---------------------------+
    | Menu                      |
    +-------+-------------------+
    | Home  |                   |
    |Client |    ContentControl |
    |Report |                   |
    +-------+-------------------+
    
    <DockPanel>
        <StackPanel DockPanel.Dock="Left">
            <Button Content="Clients" Click="Clients_Click"/>
            <Button Content="Projects" Click="Projects_Click"/>
        </StackPanel>
        <ContentControl Name="MainContent"/>
    </DockPanel>
    
    private void Clients_Click(object sender, RoutedEventArgs e)
    {
        MainContent.Content = new ClientsView();
    }
    
    private void Projects_Click(object sender, RoutedEventArgs e)
    {
        MainContent.Content = new ProjectsView();
    }
    

ScrollViewer

  • Scrollviewer is used to make your content scrollable when it exceeds the available space
  • You can use it to wrap any content that might overflow, such as long lists, large images, or complex layouts.
  • Some controls like ListBox, DataGrid, and RichTextBox have built-in scrolling capabilities, but you can use ScrollViewer for custom content or layouts that require scrolling.
    <ScrollViewer Width="300" Height="100" VerticalScrollBarVisibility="Auto">
        <StackPanel>
            <TextBlock Text="Item 1" FontSize="20"/>
            <TextBlock Text="Item 2" FontSize="20"/>
            <TextBlock Text="Item 3" FontSize="20"/>
            <TextBlock Text="Item 4" FontSize="20"/>
            <TextBlock Text="Item 5" FontSize="20"/>
            <TextBlock Text="Item 6" FontSize="20"/>
            <TextBlock Text="Item 7" FontSize="20"/>
            <TextBlock Text="Item 8" FontSize="20"/>
            <TextBlock Text="Item 9" FontSize="20"/>
            <TextBlock Text="Item 10" FontSize="20"/>
        </StackPanel>
    
    | Property | Description | | ---------|-------------| | HorizontalScrollBarVisibility | Controls the visibility of the horizontal scrollbar| | VerticalScrollBarVisibility | Controls the visibility of the vertical scrollbar|

Grid Splitter

  • GridSplitter is used to resize the grid columns or rows at runtime
  • You have to add extra row or column in your grid to add GridSplitter control with 5-10 thickness to make it visible and resizable
     <GridSplitter Grid.Column="1" Width="10" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
    

Expander

  • Expander is used to show/hide the content on click of header
  • You can use it to create collapsible sections in your UI
    <Expander Header="More Options" Width="200" Height="100">
        <StackPanel>
            <CheckBox Content="Option 1"/>
            <CheckBox Content="Option 2"/>
            <CheckBox Content="Option 3"/>
        </StackPanel>
    </Expander>
    

GroupBox

  • It's similar to what we use on windows form for grouping of similar controls
    <GroupBox
        Name="PersonGroupBox"
        Header="Personal Information"
        Width="300"
        Height="200"
        FontSize="14"
        HorizontalAlignment="Left"
        VerticalAlignment="Top">
        <StackPanel Margin="10">
            <TextBox Name="FirstNameTextBox" Margin="0,0,0,10" />
            <TextBox Name="LastNameTextBox" Margin="0,0,0,10" />
            <Button Name="SubmitButton" Content="Submit" Width="100" />
        </StackPanel>
    </GroupBox>
    
<Menu
    Name="MainMenu"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Top">
    <MenuItem Header="File">
        <MenuItem Header="New" Click="New_Click"/>
        <MenuItem Header="Open" Click="Open_Click"/>
        <MenuItem Header="Save" Click="Save_Click"/>
        <Separator/>
        <MenuItem Header="Exit" Click="Exit_Click"/>
    </MenuItem>
    <MenuItem Header="Edit">
        <MenuItem Header="Cut" Click="Cut_Click"/>
        <MenuItem Header="Copy" Click="Copy_Click"/>
        <MenuItem Header="Paste" Click="Paste_Click"/>
    </MenuItem>
</Menu>

TabControl

  • TabControl is used to group multiple pages in same window
  • Not used much in mordern apps due to side bars
  • You can use it to group related information about same object when you're space limited like settings

<TabControl>

    <TabItem Header="Client">
        <TextBlock Text="Client Information"
                    FontSize="20"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"/>
    </TabItem>

    <TabItem Header="Project">
        <TextBlock Text="Project Information"
                    FontSize="20"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"/>
    </TabItem>

    <TabItem Header="Invoice">
        <TextBlock Text="Invoice Information"
                    FontSize="20"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"/>
    </TabItem>

</TabControl>
+--------------------------------+
| Client | Project | Invoice     |
+--------------------------------+
|                                |
|      Client Information        |
|                                |
+--------------------------------+