Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Windows Phone 7.5 Data Cookbook
Windows Phone 7.5 Data Cookbook

Windows Phone 7.5 Data Cookbook: Over 30 recipes for storing, managing, and manipulating data in Windows Phone 7.5 Mango applications.

eBook
₱1616.99 ₱1796.99
Paperback
₱2245.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Windows Phone 7.5 Data Cookbook

Chapter 1. Data Binding to UI Elements

In this chapter, we will cover:

  • Element Binding

  • DataContext

  • DataTemplates

  • How DataMode is used

  • Converting data for display

  • Building a Simple App

Introduction


Data binding in Windows Phone 7 is basically connecting the UI Element with any data source. The data source may be a CLR Object, File, XML, RSS/Atom, SQL Server Database, ODATA, or any web service. The data source can reside on either on-device or external sources. Data binding is a powerful feature that makes it easy to tie UI elements to data elements in one simple property.

In this chapter, we will look into different aspects of data binding. In the first recipe we will learn how to declare Binding properties for a textbox element. Then, you will be introduced to DataContext, which is very important for connecting the data to UI elements. DataContext is also very important for separating the View from the Model, which is used in the MVVM (Model-View-ViewModel) pattern. We will learn how DataTemplates make it easy to reuse templates. DataMode helps in setting the Databinding to one way or two way updates. Notification sends the refresh notification to UI elements that data has been updated. Finally, we will learn about Converters and how they can be used to convert and format the displayed data.

Element binding


In our first recipe, let's learn how to create XAML elements and about data binding to another control like textbox using the ElementName property of the binding object.

Getting ready

  1. Open the Visual Studio for Phone 7 and create a Windows Phone Application. Name the application Recipe1 and click on OK.

  2. A shell application with default files is added as shown in the following screenshot. Notice that there are several files added to the project by default. The App.xaml file contains the App constructor with different App event handlers included in the App.xaml.cs file. There are three image files; ApplicationIcon.png is for the App Icon displayed in the Phone, Background.png is the default background image of the app, and SplashScreenImage.jpg can be used for flashing the screen before the app launches. MainPage.xaml is the main page to be displayed when the app is launched. This is where we add all the display elements for the application. The MainPage.xaml.cs file is where all the code is added to manipulate the data.

  3. After you open the project, just press F5 and run it to make sure there are no errors. It is good practice to run the app as often as you can so you can resolve any issue, otherwise you end up accumulating too many bugs.

How to do it...

Let's build a simple display page where we have one textbox to enter data and a text block to display it. When you enter text in the textbox you will see it is displayed in the display text block.

  1. Let's change the application title and the page title text blocks in the MainPage.xaml.cs file. Open the file and look for StackPanel with Name TitlePanel.

    <!--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="Ch1 Recipes" Style="{StaticResource PhoneTextNormalStyle}"/>
      <TextBlock x:Name="PageTitle" Text="Element Name" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>

    Tip

    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

  2. In order to display two columns and three rows, we should change the Grid ColumnDefinition and RowDefinition as illustrated in the XAML snippet. Locate this inside the Grid named LayoutRoot:

    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="81"/>
      <RowDefinition Height="526*"/>
    </Grid.RowDefinitions>
    
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="159*"></ColumnDefinition>
      <ColumnDefinition Width="321*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
  3. Add three TextBlock elements and a text element inside the ContentPanel grid. Here we will add binding information to the tbNameDisplayContent control. ElementName is assigned to TextBox control name. Path is assigned to the Text property of the TextBox control; this is where the data is fetched.

    <Grid x:Name="ContentPanel" Grid.Row="1" Grid.RowSpan="2" Grid.ColumnSpan="2" Margin="0,0,0,-16">
    
      <TextBlock x:Name ="tbName" Text ="Name:" Margin="2,13,371,582" />
    
      <TextBox x:Name ="txtNameContent" Text ="" Margin="128,0,6,567" />
    
      <TextBlock x:Name ="tbNameDisplay" Text ="Display Name:" Height="43" VerticalAlignment="Top" Margin="2,94,0,0" HorizontalAlignment="Left" Width="133" />
    
      <TextBlock x:Name ="tbNameDisplayContent" Text ="{Binding     ElementName=txtNameContent, Path=Text}" Margin="140,100,24,505" />
    
    </Grid>
  4. Press F5; now enter a name in the textbox and as you type you will see the text in the display text block, as shown in the following screenshot. This is the power of Data Binding.

How it works...

We used the Binding class in the XAML using the following shorthand syntax:

<object property="{Binding ElementName=name, Path=property}" …/>

You can either use Path=Name or just the name in the property Path. We set the binding information to the Content property of the TextBlock control. We used ElementName as the textbox control name and then we assigned the textbox control's Text property to the Path. Basically, the data source for the binding is the Text property of the textbox.

There's more...

In the last recipe, we learned how to use Binding with ElementName and Path. Similar to Path, we can use many properties like Converter, Mode, StringFormat, and so on. We will discuss the usage of these properties in the next several recipes in this chapter. For more information on Binding check this MSDN article:

http://msdn.microsoft.com/en-us/library/ms752347.aspx

See also

Check the recipes on How DataMode is used and Converting data for display in this chapter. Also, check the next recipe, which discusses the important concept of DataContext.

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.

Data Templates


Data Templates are a very powerful feature in XAML. Data Templates can be reusable within element level or application level. In this recipe, let's use the Data Template in the listbox control.

Getting ready

Let's create a new project using the template Ch1_Recipe and rename it as Ch1_Recipe3.

How to do it...

  1. In this recipe we will give priority to the ListBox control.

  2. Open the MainPage.xaml file, locate the Grid with the name ContentPanel and add a TextBlock and a ListBox after the last text block control. The ListBox control will contain ItemTemplate in which DataTemplate is added.

    <!-- List box priority -->
    <TextBlock x:Name ="tbPriority" Text ="Priority:" Grid.Row="3" Grid.Column ="0" />
    
    <ListBox x:Name ="lstPriority" Grid.Row="3" Grid.Column ="1">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <Border Name="border" BorderBrush="Red" BorderThickness="1" Padding="5" Margin="5">
    
            <StackPanel>
              <TextBlock x:Name ="tbPriorityContent" Text ="{Binding}" />
            </StackPanel>
          </Border>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>
  3. Let's initialize the Listbox in the code behind the XAML file, MainPage.xaml.cs, using the ItemsSource property of the ListBox. ItemSource is a collection property. Add the following code inside the MainPage constructor before the initialization:

    lstPriority.ItemsSource = new string[] { "Low", "Medium", "High" };
  4. Press F5 to see how the ListBox is filled with Low, Medium, and High values. Also, notice how the ListBox behavior changes with the Border style.

How it works...

A Data Template is the most flexible way to display data in XAML. It can include all the XAML controls like button, text blocks, textboxes, data grid, and so on. Here in the ListBox control, a Data Template is applied to all the items in the listbox along with all the formatting properties. We applied the Red border to the items in the DataTemplate mark-up.

There's more...

To understand more on Data Templates check the following article:

http://msdn.microsoft.com/en-us/library/ms742521.aspx

See also

Check the recipe named DataContext to understand more on data context concepts.

How DataMode is used


In this recipe let's understand the DataMode property of the Binding class. By default, the Data Mode property is OneWay. It has two other modes, OneTime and TwoWay . OneTime mode pulls the data only once from the source. OneWay mode only pulls the data from the source and updates it every time the source changes. TwoWay mode not only pulls the data from the source, but also pushes the changes back. These settings are not only used for data sources, they can also be tied to another element. Let's learn how we can use a TwoWay mode for the slider control to indicate the changes in a text block.

Getting ready

Create a new solution from the template Ch1_Recipe and name it Ch1_Recipe4_Mode.

How to do it...

  1. Open the MainPage.xaml page and add a text block and a slider control to the existing page after the Notes text block. Here the slider control's value property is set to bind to text block control tbPriorityContent.

    <TextBlock x:Name ="tbPriorityContent" Text ="{Binding Priority}" Grid.Row="3" Grid.Column ="1" />
    
    <Slider x:Name ="slPriority" Width="300" Minimum="1" Maximum="10" Grid.Row="4" SmallChange="10" Grid.ColumnSpan ="2" Orientation="Horizontal" HorizontalAlignment="Left" Value="{Binding ElementName=tbPriorityContent, Path=Text,   Mode=TwoWay}" />
    
  2. Open the DataClass.cs file and add another property called Priority to the DataClass, as follows:

    public class DataClass
    {
      public string Name { get; set; }
      public string Notes { get; set; }
      public int Priority { get; set; }
    }
  3. Open the MainPage.xaml.cs file and add another line in the object initializer to set the Priority to 8. This is illustrated in the following code:

    public MainPage()
    {
      InitializeComponent();
      // Initialize our data class
      myData = new DataClass()
      {
        Name = "Name 1",
        Notes = "Note 1",
        Priority = 8
      };1
    
      // Set the DataContext of the grid to DataClass
      LayoutRoot.DataContext = myData;
  4. Press F5 to run the app. As we set the priority to 8, the slider will move automatically based on the text block tbPriorityContent content. Also, try to move the slider position and you will see the text block value also changing.

How it works...

You noticed that when the slider changes its position the priority text block gets updated automatically. Because of the two-way mode setting the text block gets the data updated in the control's property as soon as it is changed. Similarly, when the text block is initialized with a value, the slider value is changed. This demonstrates how the controls can be refreshed with two-way mode.

There's more...

To learn more on the Data Bindings topic check this MSDN article:

http://msdn.microsoft.com/en-us/library/ms752347.aspx

See also

Check the recipes titled Element Binding and DataContext to learn more about these topics. Also, check the recipe Building a Simple App.

Converting data for display


On many occasions, we need to convert the data coming from the source into a form that is suitable for users to read. For example, we want to format a date as short date. In this recipe, let's add a date field to our CLR object and use the binding converter to display short date instead of long date.

Getting ready

For this recipe, let's copy the preceding project and name the new project as Recipe5. You can also do this by exporting the preceding project as a template and then creating the new project from this saved template.

How to do it...

  1. Open the DataClass.cs file from the solution window. Add a new property DateCreated:

    public class DataClass
    {
      public string Name { get; set; }
      public string Notes { get; set; }
      public int Priority { get; set; }
      public DateTime DateCreated { get; set; }
    }
  2. Add another class; as we are formatting the Date value, let's name it DateFormatter. In order for this class to inherit IValueConverter, you should use the System.Windows.Data namespace. Now add two functions Convert and ConvertBack:

    public class DateFormatter : IValueConverter
    {
      public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
        string formatString = parameter as string;
        if (!string.IsNullOrEmpty(formatString))
        {
          return string. Format(culture, formatString, value);
        }
        return value.ToString();
      }
      public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
        throw new NotImplementedException();
      }
    }
  3. Open the MainPage.xaml and let's add the namespace at the top first as PhoneApplicationPage attribute.

    xmlns:local="clr-namespace:Recipe5">
  4. Now Add the Resource markup as shown in the following code snippet:

        <phone:PhoneApplicationPage.Resources>
            <local:DateFormatter x:Key ="FormatConverter" />
        </phone:PhoneApplicationPage.Resources>
  5. Now, add two TextBlock controls for DateCreated column inside the ListBox control as shown in the following code snippet. Notice how the Converter property is set to a static resource with a converter parameter.

    <TextBlock x:Name ="tbDateCreated" Text ="DateCreated:" Grid.Row="5" Grid.Column ="0" />
    <TextBlock x:Name="tbDateCreatedContent" Grid.Row="5" Grid.Column ="1" Text="{Binding DateCreated,Converter={StaticResource FormatConverter}, ConverterParameter=\{0:d\}}" /> 
  6. Add initialization data for the DateCreated field in the code behind the XAML file:

    myData.DateCreated = DateTime.Now;
  7. Press F5 to run the code and you should see the following results:

How it works...

You can see that the DateCreated field is shorter than before. Converters are used for displaying the correct format of the data for users. In this recipe, DateFormatter uses string format to convert the date format. Similarly, various other conversions such as currency and percentage can be performed.

There's more...

You can learn deeper concepts related to data binding using this online resource:

http://msdn.microsoft.com/en-us/library/ms752039.aspx

See also

Check the recipes titled DataContext and How DataMode is used in this chapter.

Building a simple app


In this final recipe of this chapter, let's make use of all the knowledge we gained and apply it to one simple MyTasks App.

Getting ready

Right-click on the solution folder from the preceding recipe and navigate to Open | New Project. Select the Windows Phone 7 application project template. Name the project Recipe5_MyTasks.

How to do it...

Let's first build the UI for this app. This app will have two pages; the first page is the main.xaml file and the second one is the add task.xaml file.

  1. Add an application bar at the bottom to provide navigation to the two pages that we are going to build in this app. The application bar is added, as shown in the following code snippet:

    <!--Sample code showing usage of ApplicationBar-->
    <phone:PhoneApplicationPage.ApplicationBar>
      <shell:ApplicationBar BackgroundColor="Orange" IsVisible="True" IsMenuEnabled="True">
        <shell:ApplicationBarIconButton IconUri="/Images/appbar.folder.rest.png" Click="ButtonFolder_Click" Text="Task Folder"/>
        <shell:ApplicationBarIconButton IconUri="/Images/appbar.add.rest.png" Click="ButtonAdd_Click" Text="Add Task"/>
      </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>
  2. Right-click on the Recipe5_MyTasks project folder and add a new folder called Images.

  3. Let's copy two images appbar.folder.rest.png and appbar.add.rest.png to this folder from \Program Files (x86)\Microsoft SDKs\Windows Phone\v7.1\Icons\light. For a non-64 bit machine, you may navigate to \Program Files\Microsoft SDKs\Windows Phone\v7.1\Icons\light.

  4. Right-click on the image files you added and select the Build Action property to Content. This will copy the images to an XAP file.

  5. Open the MainPage.xaml.cs file and add two button event methods. The first button event, ButtonFolder_Click, uses the NavigationService class to navigate to MainPage.xaml. The second button event, ButtonAdd_Click, navigates to AddTask.xaml file:

    private void ButtonFolder_Click(object sender, EventArgs e)
    {
      NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
    }
    
    private void ButtonAdd_Click(object sender, EventArgs e)
    {
      NavigationService.Navigate(new Uri("/AddTask.xaml", UriKind.Relative));
    }
  6. Open the Main.xaml file and add the list box with its data template:

    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Margin="12,0,12,-13" Grid.Row="1">
      <ListBox x:Name ="lstTasks" Grid.Row="3" Grid.Column ="1">
        <ListBox.ItemTemplate>
          <DataTemplate>
            <Grid>
              <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition />
                <RowDefinition Height="15" />
              </Grid.RowDefinitions>
    
              <Grid.ColumnDefinitions>
                <ColumnDefinition Width="150" />
                <ColumnDefinition Width="200" />
                <ColumnDefinition Width="100" />
              </Grid.ColumnDefinitions>
    
              <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Name}" />
              <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding DateDue}" />
              <TextBlock Grid.Row="0" Grid.Column="2" Text="{Binding Priority}" Forground = "{StaticResource PhoneAccentBrush}" />
              <TextBlock Grid.Row="1" Grid.ColumnSpan="3" Text="{Binding Notes}" />
              <TextBlock Grid.Row="2" Grid.ColumnSpan="3" />
            </Grid> 
          </DataTemplate>
        </ListBox.ItemTemplate>
      </ListBox>
    </Grid>
  7. Open the AddTask.xaml file and add four text blocks in the ContentPanel grid:

    <!--ContentPanel - place additional content here-->
    <TextBlock x:Name="tbName" HorizontalAlignment="Left" TextWrapping="Wrap" Text="Name" VerticalAlignment="Top" />
    <TextBlock x:Name="tbDescription" HorizontalAlignment="Left" Margin="8,70,0,0" TextWrapping="Wrap" Text="Description" VerticalAlignment="Top" />
    <TextBlock x:Name="tbPriority" HorizontalAlignment="Left" Margin="8,150,0,0" TextWrapping="Wrap" Text="Priority" VerticalAlignment="Top" />
    <TextBlock x:Name="tbDueDate" HorizontalAlignment="Left" Margin="8,277,0,0" TextWrapping="Wrap" Text="Due Date" VerticalAlignment="Top"/>
  8. Now add corresponding textbox controls for each one, as follows:

    <TextBox x:Name="txtName" Margin="119,0,70,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
    <TextBox x:Name="txtDescription" Margin="119,62,70,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
    <TextBox x:Name="txtDueDate" Margin="119,262,74,298" TextWrapping="Wrap"/>
    <Button x:Name="btnAdd" Content="Add"  Margin="131,0,205,225" VerticalAlignment="Bottom" RenderTransformOrigin="0.969,0.514" Click="btnAdd_Click" />
    <Button x:Name="btnCancel" Content="Cancel" HorizontalAlignment="Right"  Margin="0,0,74,225" VerticalAlignment="Bottom" Click="btnCancel_Click" />
    <ListBox x:Name="lsyPriority" Margin="131,154,84,0" VerticalAlignment="Top">
      <ListBoxItem Content="Low"/>
      <ListBoxItem Content="Medium"/>
      <ListBoxItem Content="High"/>
    </ListBox>
    </Grid>
  9. Right-click on the project folder and add a new class file. Name it DataClass.cs. Now, add the following DataClass with all its properties. If you compare this class with the preceding recipes, for simplicity we changed int Priority to string Priority and added one more DateTime property called DateDue.

    public class DataClass
    {
      public string Name { get; set; }
      public string Notes { get; set; }
      public string Priority { get; set; }
      public DateTime DateDue { get; set; }
      public DateTime DateCreated { get; set; }
    }
  10. Open the MainPage.xaml.cs file and add the using statement for the reference System.Collections.ObjectModel.

    using System.Collections.ObjectModel;
  11. ObeservableCollection is the collection class that we will use for building our task collection. Observable Collection provides the notifications whenever items get added or removed. Add the following line of code before the MainPage constructor method in the MainPage.xaml.cs file:

    private ObservableCollection<DataClass> myTasks;
  12. Let's add a method to initialize myTasks:

    private void InitalizeTasks()
    {
      myTasks = new ObservableCollection<DataClass>();
      DataClass myTask1 = new DataClass()
      {
        Name = "Task Name 1",
        Notes = "Task Note 1",
        Priority = "Low",
        DateDue = new DateTime(2011, 9, 1),
        DateCreated = DateTime.Now
      };
      myTasks.Add(myTask1);
    
      DataClass myTask2 = new DataClass()
      {
        Name = "Task Name 2",
        Notes = "Task Note 2",
        Priority = "Medium",
        DateDue = new DateTime(2011, 10, 1),
        DateCreated = DateTime.Now
      };
      myTasks.Add(myTask2);
    
      DataClass myTask3 = new DataClass()
      {
        Name = "Task Name 3",
        Notes = "Task Note 3",
        Priority = "High",
        DateDue = new DateTime(2011, 11, 1),
        DateCreated = DateTime.Now
      };
      myTasks.Add(myTask3);
    }
  13. Initialize this in the MainPage constructor and assign the myTasks collection to the listbox itemsource property:

    public MainPage()
    {
      InitializeComponent();
      InitalizeTasks();
      lstTasks.ItemsSource = myTasks;
    }
  14. Press F5 and check out the results.

How it works...

In this recipe we created a display of the list of tasks in the ListBox and a form to add a new task to the list.

We initialized the tasks using the ObeservableCollection class and then added static data to this collection using the Add method.

Once the collection was built, we bound this list to ListBox for display. We added a navigation bar using the built-in ApplicationBar and then added two icons, one for adding a task to the list and another for navigating back to the main page.

There's more...

In the previous recipe, we mainly covered how to create the data binding for the main page list and then navigate to a new form to add the task. We can also add another important feature to select a list item and then update the existing data.

See also

Check the recipes in Chapter 2, Isolated Storage, to learn how to save the tasks to local storage. Also, check Chapter 3, XML as a Data Store, to learn how to save the tasks to XML files.

Left arrow icon Right arrow icon

Key benefits

  • Simple data binding recipes to advanced recipes for building scalable applications
  • Techniques for managing application data in Windows Phone mango apps
  • On-device data storage, cloud storage and API interaction.

Description

Windows Phone 7.5 Mango contains support for apps written in Silverlight or XNA. These apps can store data on the device, and also load and manipulate data from "the cloud" and other web services.This Windows Phone 7.5 Data Cookbook has a range of recipes to help you apply data handling concepts. You will be able to apply the knowledge gained from these recipes to build your own apps effectively. This Windows Phone 7.5 Data Cookbook starts with data binding concepts at the UI layer and then shows different ways of saving data locally and externally in databases. The book ends with a look at the popular MVVM software design pattern. The recipes contained in this book will make you an expert in the areas of data access and storage.

Who is this book for?

This book is for developers who want to build data-driven apps, or a line of business applications using the Windows Phone platform. It is also useful for developers on other mobile platforms looking to convert their apps to Windows Phone 7.5 Mango. Basic understanding of C#, XAML and Silverlight is required.

What you will learn

  • Create data binding to user interface elements with any data source
  • Create and save user settings to local isolated storage for later consumption.
  • Explore different on device database options such as commercial Perst, open source SQLite and Microsoft’s SQL CE.
  • Create and consume simple web services and understand LINQ features.
  • Scale the applications and work with WCF web services.
  • Understand REST and call different social media services like Twitter and RSS Feeds.
  • Create and understand MVVM model.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 28, 2011
Length: 224 pages
Edition : 1st
Language : English
ISBN-13 : 9781849691239
Vendor :
Microsoft
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Oct 28, 2011
Length: 224 pages
Edition : 1st
Language : English
ISBN-13 : 9781849691239
Vendor :
Microsoft
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 6,175.97
Windows Phone 7.5: Building Location-aware Applications
₱1122.99
Windows Phone 7 Silverlight Cookbook
₱2806.99
Windows Phone 7.5 Data Cookbook
₱2245.99
Total 6,175.97 Stars icon

Table of Contents

8 Chapters
Data Binding to UI Elements Chevron down icon Chevron up icon
Isolated Storage Chevron down icon Chevron up icon
XML as a Data Store Chevron down icon Chevron up icon
Using Open Data Chevron down icon Chevron up icon
Using On-Device Databases Chevron down icon Chevron up icon
Representational State Transfer—REST Chevron down icon Chevron up icon
Windows Communication Framework—WCF Chevron down icon Chevron up icon
Model View ViewModel Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(6 Ratings)
5 star 66.7%
4 star 16.7%
3 star 16.7%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Tamer Maher Dec 28, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I `ve recently read "Windows Phone 7.5 Data Cookbook" . The book covers different database related alternatives in a chapter to chapter basis. You can read what you want without having to read the book from cover to cover. Chapters discuss different topics without being dependent on each other's.The book mainly targets experienced Windows Phone developers. The book aims at boosting your mobile database development skills. If you are not familiar with programming C#.net, Silverlight and other necessary development skills , then, you have to check some extra books too for the basics. But if you have been writing some Windows Phone applications and had some hard times with the database stuff, then you are in the right place.The book uses the latest updates in Windows Phone 7.1 SDK that enable developers write applications for the latest version Windows Phone 7.5The book discusses new stuff like Twitter , Atom and RSS, and mobile specific database connections using JSON, also the conventional powerful SQLite. and SQLCE . LINQ to SQL and ADO.net.There are some examples using REST and WCF and the new Model View View Model (MVVM ).The book uses a simple coding style, straight and to the point, without confusing the reader with complex code that doesn't add a value. After having hands on every topic separately, at the end of each chapter, you have a sum-up sample app where you combine all the knowledge you gained in the chapter in one single app to see how things fit together in the big picture.The book also uses examples that can be implemented in the real world, so you learn fast, improve your skills, and you don't have to reinvent the wheel.Although the book is great in discussing the different data alternatives, it should have made a comparison between the different alternatives and discussing pros and cons of each using different case studies showing when to use each alternative rather than another.Overall: that is a really good book.
Amazon Verified review Amazon
Steve G Dec 29, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Having written a couple of WP7 applications I was looking for a book that was small, consist, and could take my applications to a whole new data centric level, and this is definitely what I found with Windows phone 7.5 Data Cookbook. I was also after a good reference guide. Don't let the 224 pages deceive you, each recipe in a chapter builds on the previous and each one provides a great example of what it's trying to teach you without getting too bogged down in "boiler plate code".As the synopsis says, I would highly recommend that the reader has some basic knowledge of c# and Silverlight before picking up this book as the book wastes very little time in explaining how to get up and running other than providing links to the required software download.At the end of each recipe the book clearly explains how each application works and also provides web links to msdn and other sites for additional learning. I thought this was a great idea as there is little point republishing what is already widely available on the internet and allows the reader to go off and develop their understand further if they so wish.One of the biggest things I liked about this book is the fact the author doesn't feel compelled to stick with just writing about windows Phone and gives the reader an understanding of numerous other technologies, including non-Microsoft products. For example Chapter 5 walks the reader through various different databases that can run on the phone from Microsoft examples to open source examples. Chapter 8 is dedicated to the MVVM pattern and the author gives the reader a good understanding of the MVVM Light framework and how to use it on the Windows Phone. Several chapters also make use of Linq and Entity framework, but they walk the reader through these subjects in a clear way that even if you haven't used the technologies before you will have a good understanding of what is going on.The book starts off with a great first chapter on data binding which is probably one of the single most important concepts of Silverlight/WP7 applications. The second chapter then dives into the various methods for storing user/application settings in the isolated storage. Chapters 3 to 7 include various different methods for pulling data down to the phone and querying it locally, from using XML files on remote servers to using OData and RESTful interfaces to WCF services and retrieval from SQL CE and SQL Lite databases. And finally Chapter 8 provides a brilliant walk through of using the MVVM pattern and then how existing open source frameworks such as MVVM Light can make the process quicker to develop.As each chapter covers a different subject area you can almost jump into a chapter and start reading and developing the examples from it. There is one exception to this and the author makes clever use of the Visual Studio templates to prevent the user having to constantly go back and develop the same piece of code over and over again. Having written the chapters with this approach, I can now easily reference parts of the book whilst writing my own applications.I would highly recommend this book to anyone starting out writing any Windows Phone application which is data centric. Read this book, it will not take very long, before writing any code!!
Amazon Verified review Amazon
ArchieCoder Dec 29, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The Windows Phone 7.5 Data Cookbook covers 99% ways to deal with data with Windows Phone programming. The book does not lose time about C# programming. It goes directly about using data on a Windows Phone.For a beginner, the book can be easily read from start to the end, because the complexity increases gradually. For an intermediate or an expert, you can just pick the topic that you are interested; this is the best thing on a "recipe" style book.Some people might say that 224 pages are not enough to go deep on all technologies, but I can't say it is not a problem because the book contains a lot of website links if you want to go further on a specific topic.The author succeeded to describe complex technology like incorporating SQL database in Windows Phone applications with the help of step-by-step images.From Isolated Storage to Windows Communication Framework, the book contains a lot of recipes that you can get new ideas for your next Windows Phone application!This book is the perfect reference guide for topics related with data.
Amazon Verified review Amazon
P. Pedireddi Dec 30, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I just bought this book. The book is written in such a way that developers with any experience level can easily grasp the contents. The chapters have been formatted very well. The example code provided is very helpful. This has lot of information. For this price of $40, it is definitely worth owning this book.
Amazon Verified review Amazon
Tim Dams Dec 09, 2011
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
The basic premises of the book is the same as the other Packt `Cookbooks': each chapter consists of several step-by-step tutorials (dubbed "recipes") , each time resulting in a mini-program with full functionality.The main application that is rebuilt each time is a simple task manager. Each chapter 3 or more recipes are shown, usually (re)building the main task application. After each chapter and recipe a short explanation and reference to online sources is given .The book is aimed at developers who have little to no WP7 experience, however a solid Silverlight understanding is a must (for any WP7 developer that is) to get the most from this book. The 8 chapters are logically ordered, each time increasing in complexity. The first 3 chapters (databinding, isolatedstorage and XML) explain topics of which an abundant amount of online tutorials exist. They didn't really add much additional value for people already familiar with the basics of WP7. Though it should be pointed out that even the first recipes always did something `cool' or new in addition to the core topic: most tutorials stop once the basic idea is explained. In chapter 2, for example, an image file is read and subsequently the image is then used as a background image for the app. It's a small addition, but it lifts this (and other) recipe to a new, more usable, real-world example instead of a basic tutorial.Chapter 4 and further on the other hand is where the fun stuff starts: OData, WCF, REST services, on-device databases (SQL Lite, SQL CE) and even a MVVM-quicky all pass along.Though the book covers a lot of stuff, it only counts a meager 207 pages: compared to Gill Cleeren's Silverlight 4 Data Services Cookbook, the biggest `loss' of pages is due to the lack of additional information being given. Basically each recipes can be followed but once you want to find out why this or that step actually works the book can't help anymore. It's also a shame that only the first few pages of code have the most important parts highlighted in bold fonts. By highlighting this code, it easy to quickly see in a big pile of XAML what the essential part is (even more once the boiler-plate code starts becoming repetitive). For some reason, the author stopped doing that after chapter 1.To conclude; the concept of independent recipes makes it ideal to pick any chapter (or recipe) and start building stuff, without any dependencies on previous chapters or recipes. The downside however is that this also results in lots of identical steps that need to be taken each recipe. For me, this book is ideal in a classroom environment: students can be given a weekly recipe to solve and expand without the need of having made previous recipes.If the idea of this cookbook is to whet one's appetite of what can be done with the new 7.5 Mango Phone, it certainly succeeds . If on the other hand you expect in-depth explanation of one or more related topics, skip this one.You can find a more in-depth, per chapter review of this book here: [...]
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.