Thursday, November 18, 2010

Layout in xaml – basic layout in wp7 applications


There are lots of ways to layout your applications. But there might be something that you should know.
1.       Listbox cannot scroll under StackPanel. So, always be sure that you place Listbox under Gird.
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
           <ListBox x:Name="MainListBox" Margin="0,0,-12,0" ItemsSource="{Binding}">
               <ListBox.ItemTemplate>
                   <DataTemplate>
                       <StackPanel>
                           ……
                       </StackPanel>
                   </DataTemplate>
               </ListBox.ItemTemplate>
           </ListBox>
        </Grid>

2.       You can use RowDefinition and Grid.Row to perfectly arrange your layout.
Firstly, define Rowdefinition under your LayoutRoot.
-          If you want to divide your page into 3 parts, you just have to define 3 RowDefinitions.
-          The parameter Height represents how much space you want to give for each part.
-            Auto:  By the height of its content.
-            72 or any other number: by pixel.
-            *: the rest. If you have two or more RowDefinitions having the * parameter, it means their height will be equal.
-            If you define two using 2* and 3*, it means one of them will be 2/5, the other will be 3/5.
-          Also, you can split the page horizontally by using ColumnDefinition.
<Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="72"/>
        </Grid.RowDefinitions>

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            ……
        </StackPanel>

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            ……
        </Grid>

        <StackPanel Grid.Row="2" Margin="12,0,12,0">
            ……
        </StackPanel>
    </Grid>

3.       In data binding, all of the layout properties can be bind.
<TextBlock Text="{Binding myText}" HorizontalAlignment="{Binding HAlignment}" Foreground="{Binding myForeground}" />

4.       HorizontalAligment will not work unless the parent object has width information.
<StackPanel Grid.Row="2" Margin="12,0,12,0">
        <TextBox HorizontalAlignment="Right"></TextBox>
    </StackPanel>