Simple Databinding and 3-D Features using Silverlight in Windows Phone 7 (WP7)

Posted by: Mahesh Sabnis , on 4/27/2010, in Category Windows Phone
Views: 60432
Abstract: Windows Phone 7 (WP7) is the upcoming next generation Mobile Operating System by Microsoft. Amongst the many features, one of the nice features is that it has support for Silverlight. So most of the new features like 3-D, Databinding etc. are now available on WP7. In this article I will explain the basic Databinding as well as 3-D feature on Windows Phone 7.
Windows Phone 7 (WP7) is the upcoming next generation Mobile Operating System by Microsoft. Amongst the many features, one of the nice features is that it has support for Silverlight. So most of the new features like 3-D, Databinding etc. are now available on WP7. In this article I will explain the basic Databinding as well as 3-D feature on Windows Phone 7. For development of WP7, you can use the VS 2010 Express 2010 for Windows Phone with the Windows Phone Developer Tools. You can get the installer from the following path:
VS 2010 Express for WP7 gives you the IDE to develop WP7 apps. This also installs Silverlight 4.0 runtime and Silverlight tools for VS 2010 (if VS2010 RC is previously installed on your machine). When you create a new Windows Phone application, you will get the following design layout:
PageLayout
On this layout, you can drag and drop controls for the UI creation. This is actually a Xaml file as shown below:
<phoneNavigation:PhoneApplicationPage
    x:Class="WindowsPhoneApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phoneNavigation="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Navigation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="800"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}">
 
    <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneBackgroundBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
 
        <!--TitleGrid is the name of the application and page title-->
        <Grid x:Name="TitleGrid" Grid.Row="0">
            <TextBlock Text="MY APPLICATION" x:Name="textBlockPageTitle" Style="{StaticResource PhoneTextPageTitle1Style}"/>
            <TextBlock Text="page title" x:Name="textBlockListTitle" Style="{StaticResource PhoneTextPageTitle2Style}"/>
        </Grid>
 
        <!--ContentGrid is empty. Place new content here-->
        <Grid x:Name="ContentGrid" Grid.Row="1">
        </Grid>
    </Grid>
   
</phoneNavigation:PhoneApplicationPage>
If you carefully look at the XAML, you will find that unlike parent UserControl in a normal Silverlight application, here a new class ‘PhoneApplicationPage’ is used. This represents phone application page for UI creation and navigation functionality. This class is inherited from the ‘Page’ class. The App.Xaml file in this project defines all the default styles for the WP7 application like Background color etc. So if you want to change the default style of the windows phone, you can do it from App.Xaml.     
When you run the project targeting an emulator, you will see an output as shown below:
PageLayout_1
The vertical bar (marked in red ellipse) near the emulator is used to control the display of the emulator. If you click on the third button in the bar from top, the display of the emulator will be in the Landscape mode as shown in the second image.
This was a very small intro to the basic features of the WP7. We are now going to develop a simple Databinding and 3-D application.
Step 1: Start the VS2010 Express for WP7 and create a new Windows Phone Application, name it as ‘WP7_SimpleDatabinding’.
AddNewProject
Step 2: Open MainPage.xaml.cs or vb and write following two classes:
C#
public class clsEmployee
{
    public int EmpNo { get; set; }
    public string EmpName { get; set; }
    public int Salary { get; set; }
}
 
public class EmployeeCollection : ObservableCollection<clsEmployee>
{
    public EmployeeCollection()
    {
        Add(new clsEmployee() { EmpNo = 101, EmpName = "EmpName_1", Salary = 1000 });
        Add(new clsEmployee() { EmpNo = 102, EmpName = "EmpName_2", Salary = 2000 });
        Add(new clsEmployee() { EmpNo = 103, EmpName = "EmpName_3", Salary = 3000 });
        Add(new clsEmployee() { EmpNo = 104, EmpName = "EmpName_4", Salary = 4000 });
        Add(new clsEmployee() { EmpNo = 105, EmpName = "EmpName_5", Salary = 5000 });
        Add(new clsEmployee() { EmpNo = 106, EmpName = "EmpName_6", Salary = 6000 });
    }
}
VB.NET
Public Class clsEmployee
      Private privateEmpNo As Integer
      Public Property EmpNo() As Integer
            Get
                  Return privateEmpNo
            End Get
            Set(ByVal value As Integer)
                  privateEmpNo = value
            End Set
      End Property
      Private privateEmpName As String
      Public Property EmpName() As String
            Get
                  Return privateEmpName
            End Get
            Set(ByVal value As String)
                  privateEmpName = value
            End Set
      End Property
      Private privateSalary As Integer
      Public Property Salary() As Integer
            Get
                  Return privateSalary
            End Get
            Set(ByVal value As Integer)
                  privateSalary = value
            End Set
      End Property
End Class
 
Public Class EmployeeCollection
      Inherits ObservableCollection(Of clsEmployee)
      Public Sub New()
            Add(New clsEmployee() With {.EmpNo = 101, .EmpName = "EmpName_1", .Salary = 1000})
            Add(New clsEmployee() With {.EmpNo = 102, .EmpName = "EmpName_2", .Salary = 2000})
            Add(New clsEmployee() With {.EmpNo = 103, .EmpName = "EmpName_3", .Salary = 3000})
            Add(New clsEmployee() With {.EmpNo = 104, .EmpName = "EmpName_4", .Salary = 4000})
            Add(New clsEmployee() With {.EmpNo = 105, .EmpName = "EmpName_5", .Salary = 5000})
            Add(New clsEmployee() With {.EmpNo = 106, .EmpName = "EmpName_6", .Salary = 6000})
      End Sub
End Class
 
Step 3: Add a new Grid control on the MainPage.Xaml and add the following controls:
·         Button.
·         ListBox.
·         Slider with 2 in number.
The Xaml will be as below:
<!--ContentGrid is empty. Place new content here-->
        <Grid x:Name="ContentGrid" Grid.Row="1">
            <Button Content="Load Data" Height="59" HorizontalAlignment="Left" Margin="76,44,0,0" Name="button1" VerticalAlignment="Top" Width="243" Foreground="#FF1937FF" Background="#FFA80000"/>
            <ListBox Height="354" HorizontalAlignment="Left"
                     Margin="11,149,0,0" Name="lstEmployees" VerticalAlignment="Top" Width="404"
                      >
                <ListBox.Projection>
                    <PlaneProjection x:Name="listProjection"></PlaneProjection>
                </ListBox.Projection>
            </ListBox>
            <Slider Height="24" HorizontalAlignment="Left" Margin="20,546,0,0" Name="sliderX" VerticalAlignment="Top" Width="397" Maximum="360" ValueChanged="sliderX_ValueChanged" />
            <Slider Height="330" HorizontalAlignment="Left" Margin="442,161,0,0" Name="sliderY" VerticalAlignment="Top" Width="14" Orientation="Vertical" Maximum="360" ValueChanged="sliderY_ValueChanged" />
        </Grid>
 
 
The above Xaml code shows that a PlaneProjection is defined for the list, so that 3-D effects can be applied on it.
The design on the WP7 emulator will be as shown below:
WP7_1
Step 4: Open MainPage.Xaml file and add the following data template:
<phoneNavigation:PhoneApplicationPage.Resources>
        <DataTemplate x:Key="EmpDs">
            <Grid Width="360">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="90"></ColumnDefinition>
                    <ColumnDefinition Width="90"></ColumnDefinition>
                    <ColumnDefinition Width="90"></ColumnDefinition>
                    <ColumnDefinition Width="90"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding EmpNo}" Grid.Column="0" Height="25"/>
                <TextBlock Text="{Binding EmpName}" Grid.Column="1" Height="25"/>
                <TextBlock Text="{Binding Salary}" Grid.Column="2" Height="25"/>
            </Grid>
        </DataTemplate>
    </phoneNavigation:PhoneApplicationPage.Resources>
 
Step 5: View the designer of WP7 and double-click on the Load Data button, you will find the click Event generated in the code behind and the <Button> in Xaml will be as shown below:
<Button Content="Load Data" Height="59" HorizontalAlignment="Left" Margin="76,44,0,0" Name="button1" VerticalAlignment="Top" Width="243" Foreground="#FF1937FF" Background="#FFA80000" Click="button1_Click" />
Open MainPage.Xaml.cs ad write the following code:
C#
 private void button1_Click(object sender, RoutedEventArgs e)
 {
         lstEmployees.DataContext = new EmployeeCollection();
           
 }
 
VB.NET
 Private Sub button1_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
             lstEmployees.DataContext = New EmployeeCollection()
 
 End Sub
This code sets the data context of the list box to the Employee data.
Step 6: Open MainPage.Xaml file and change the <ListBox> shown below:
<ListBox Height="354" HorizontalAlignment="Left"
                     Margin="11,149,0,0" Name="lstEmployees" VerticalAlignment="Top" Width="404"
                      ItemsSource="{Binding}"
                      ItemTemplate="{StaticResource EmpDs}">
                <ListBox.Projection>
                    <PlaneProjection x:Name="listProjection"></PlaneProjection>
                </ListBox.Projection>
</ListBox>
 
This binds the Employee data with the list box and defines a visual tree for the list to multicolumn using ItemTemplate. This is assigned by the data template defined in the resources.
Here if you carefully observe the MainPage constructor, you will find the code below:
C#
public MainPage()
{
    InitializeComponent();
 
    SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
    
}
VB.NET
Public Sub New()
      InitializeComponent()
 
      SupportedOrientations = SupportedPageOrientation.Portrait Or SupportedPageOrientation.Landscape
 
End Sub
The ‘SupportedOperations’ defines the display of the content inside the PhoneApplicationpage. This operation is self explanatory.
Step 7: Write ‘ValueChaged’ for both the sliders as shown below:
C#
private void sliderX_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
    listProjection.RotationX = sliderX.Value;
}
 
private void sliderY_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
    listProjection.RotationY = sliderY.Value;
}
VB.NET
Private Sub sliderX_ValueChanged(ByVal sender As Object, ByVal e As RoutedPropertyChangedEventArgs(Of Double))
      listProjection.RotationX = sliderX.Value
End Sub
 
Private Sub sliderY_ValueChanged(ByVal sender As Object, ByVal e As RoutedPropertyChangedEventArgs(Of Double))
      listProjection.RotationY = sliderY.Value
End Sub
These changes the projection values for the ListBox control.
Step 8: Run the application, click on ‘Load Data’ button and the output will be as shown below in first column:
WP7_2
Change the slider values and it will show a 3-D rotation across X and Y axis as per the results in the second column above.
Step 9: Click on the buttons on the attached bar with the emulator and the result will be shown as below
WP7_3
Now this is not the display as expected. So to display the result correctly, change the code in the MainPage constructor as below:
SupportedOrientations = SupportedPageOrientation.Portrait;
Run the project and the result will be as shown below:
WP7_4
Conclusion: Windows Phone 7 has provided nice features for providing Rich UX to the end user. With the Silverlight integration on WP7, it is possible mobile developers to provide excellent user experiences to end users.     
The entire source code of this article can be downloaded over here
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Gergely Orosz on Tuesday, April 27, 2010 6:46 AM
Small Clarification: WP7 doesn't support Silverlight 4 at the moment. It supports only an extended Silverlight 3.
Comment posted by Admin on Tuesday, April 27, 2010 7:17 AM
Gergely: Thanks. We have removed the version number from the post.

Additional details: http://www.silverlighthack.com/post/2010/03/16/Silverlight-for-Windows-Phone-7-is-NOT-the-same-full-Silverlight-3-RTM.aspx

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel