Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Windows Phone 7.5 Data Cookbook

You're reading from   Windows Phone 7.5 Data Cookbook Over 30 recipes for storing, managing, and manipulating data in Windows Phone 7.5 Mango applications.

Arrow left icon
Product type Paperback
Published in Oct 2011
Publisher Packt
ISBN-13 9781849691222
Length 224 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Ramesh Thalli Ramesh Thalli
Author Profile Icon Ramesh Thalli
Ramesh Thalli
Arrow right icon
View More author details
Toc

DataContext


In the last recipe, we discussed how the data binding is done at the element level. In this recipe, let's add some CLR Object and use the DataContext to link a Databound element and the property in the CLR Object.

Getting ready

Let's create a new project for this recipe. Right-click on the last solution folder Ch1_Recipes and Add | New Project, select the Windows Phone Application Template, and name it Ch1_Recipe2.

How to do it…

Here, let's create a simple application to tie data elements with a CLR Object. A data class with just two properties is created and then initialized to some test data. Then, it is assigned to the data context.

  1. Right-click on Ch1_Recipe2 and Add | Class.

  2. Create the class, name it DataClass and add just two string properties; one called Name and the other Notes:

    namespace Recipe2
    {
      public class DataClass
      {
        public string Name { get; set; }
        public string Notes { get; set; }
      }
    }
  3. Open the MainPage.xaml file and change the ApplicationTitle and PageTitle as shown in the following code snippet:

    <!--TitlePanel contains the name of the application and page title-->
    
    <StackPanel x:Name="TitlePanel" Grid.Row="0" Grid.ColumnSpan ="2">>
      <TextBlock x:Name="ApplicationTitle" Text="Phone7 Recipes" Style="{StaticResource PhoneTextNormalStyle}"/>
      <TextBlock x:Name="PageTitle" Text="Object Bindings" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>
  4. In order to display two columns and three rows, we should change the Grid ColumnDefinition and RowDefinition as illustrated in the following XAML snippet:

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
      <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="50"/>
        <RowDefinition Height="*"/>
      </Grid.RowDefinitions>
    
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="74*"></ColumnDefinition>
        <ColumnDefinition Width="406*"></ColumnDefinition>
      </Grid.ColumnDefinitions>
  5. Let's add two TextBlock controls to display Name and Notes. Here the Name and Notes are referring to the properties of the Object DataClass. Add four TextBlock elements inside the ContentPanel grid; here we will add binding information to display both elements tbNameContent and tbNoteContent. Binding objects tie a name to a control object without knowing where it comes from, as follows:

    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Grid.RowSpan="2" Grid.ColumnSpan="2" Margin="0,0,0,-16">
    
      <TextBlock x:Name ="tbName" Text ="Name:" Grid.Row="1" Grid.Column ="0"/>
    
      <TextBlock x:Name ="tbNameContent" Text ="{Binding Name}" Margin="74,0,6,567" />
    
      <TextBlock x:Name ="tbNotes" Text ="Notes:" Height="43" VerticalAlignment="Top" Margin="0,85,412,0" />
    
      <TextBlock x:Name ="tbNotesContent" Text ="{Binding Notes}" Margin="74,85,0,16" />
    </Grid>
  6. Press F5. Now you will see the two display items without any data, as follows:

  7. Open the MainPage.xaml.cs file. First, create a private variable for DataClass before the MainPage constructor. In the MainPage constructor, initialize the DataClass object with sample data using the object initializer as shown in the following code snippet. Finally, myData object is assigned to DataContext, which updates the text blocks with the data.

    namespace Recipe2
    {
      public partial class MainPage : PhoneApplicationPage
      {
    
        private DataClass myData;
    
        // Constructor
        public MainPage()
        {
          InitializeComponent();
          // Initialize data class
          myData = new DataClass()
          {
            Name = "Name 1",
            Notes = "Note 1"
          };
    
          // Set the DataContext of the grid to DataClass Object
          LayoutRoot.DataContext = myData;
       }
      }
    }
  8. Press F5. Now test data, which is initialized in the code behind the file, is displayed.

How it works...

Initially, we set the Binding properties of the elements to DataClass property names. Here the binding enables us to set the property names without actually knowing how they will be assigned later. Magic happens through the DataContext. The DataContext of the elements allows inheriting the information about the data, used for data binding, from their parent elements. Hence, setting the DataContext of Layoutroot to the DataClass object automatically applied to the text block elements with its properties.

There's more...

For more understanding of the DataContext class, check this MSDN resource online:

http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontext.aspx

How to export the project as a template

We will learn how to use Recipe2 as a template so you can easily reuse the project as a starter application for future projects. You can export any of the projects you are working on as a template for future use.

  1. Open the previous project Recipe2.

  2. Go to File | Export Template.

  3. Select the default project template as the option, which is Recipe1.

  4. Fill in the Template Name Ch1_Recipe and click on Finish. The template is saved to your project template folder. Now, all the files are copied as a part of the project template Ch1_Recipe.

See also

Check the first recipe Element Binding to learn more about bindings. Also, check the next recipe on Data Templates.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image