Over a million developers have joined DZone.

31 Days of Mango | Day #18: Using Sample Data

· Mobile Zone

Visually compose APIs with easy-to-use tooling. Learn how IBM API Connect provides near-universal access to data and services both on-premises and in the cloud, brought to you in partnership with IBM.

This article is part of a series called 31 Days of Mango.

Day18-ExpressionBlendSampleData

Today, we are going to explore another great feature of Expression Blend by creating some sample data that our application can use.  Many times, when you start building an application, you want to see what the data will look like in the user interface well before the database (or web service) is actually ready.  To do this, we can use Expression Blend.

Since I have covered Expression Blend and many of its features in the past, I’ll give you some recommended reading here:


For today’s article, we’re just going to dive right in.

Creating Your Windows Phone Application

As with most of my posts in this series, I have also created a video to demonstrate what I am trying to accomplish with this article.  I will explain everything that is shown in the video, but if you’d prefer to watch it first, here it is:





We will start by creating a new Windows Phone project.  You’ve hopefully done this many times already in Visual Studio 2010, so I will walk you through doing this in Expression Blend this time.

image

Once you have your new project, with your MainPage.xaml page open, we are going to add a ListBox to our page.  To do this, click the arrow in the left-side menu bar, choose controls, and click the ListBox icon.

image

Once you’ve selected the ListBox, you can click and drag one on to your design surface.

image

I’ve expanded my ListBox to take up the entire space inside my ContentPanel Grid that was created by default when I created my project.  (This is all of the space below the “page name” text on the screen.

Creating Some Sample Data

If you look in the top right corner of Expression Blend, you should see a tab with the word “Data” on it.  Open that tab.

image

By clicking the “New Sample Data” button on the top right of this panel, we will be able to get started creating our sample data.

image

This will bring up the “New Sample Data” dialog box.  Give your data a name (I named mine Furniture, to follow the example that I used in the video.)

image

You’ll notice that you have the option to define this data in your project, or on the specific page.  I recommend choosing “Project” because it will create a bunch of useful structures in your application that you can use in a more permanent fashion.

Clicking OK will take you back to the Data tab, with a few new things added.

image

We now have a structure that should look familiar to anyone that has worked with a database before.  “Furniture” represents our database, and “Collection” is a table in that database.  “Property1” and “Property2” are fields in the Collection table.

I am going to add two new properties to the database, and rename the existing two, so that things are a little more descriptive.  Collection will become “Chairs”, and we now have 4 properties: SKU, Price, Description, and Image.

image

At the right end of each of the properties, there is an icon to indicate what type of data it is.  For Description, I want it to be a long string of words.  You can do this by choosing the “Lorem Ipsum” string type.  This will give us random strings of 20 words, with no word being longer than 8 characters.

image

We want the Image property to actually contain images, so you should choose the Image type.  You can specify your own set of images if you’d like, and we’ll do that later in this article.

image

I will quickly set the Price property to a String/Price type, and the SKU to be a Number value, with 6 character values.

imageimage

If you click on the “View Sample Data” button to the right of the “Chairs” title, you will be shown a grid of data that contains randomized data for each of the properties we have specified.  By changing the value of the “Number of records” box at the bottom, you can determine how many data records you would like to use.

SNAGHTML27ad8b6d

So there you have it.  We’ve created some sample data.  At this point, you’re probably staring at the sample data above trying to figure out how it knew to use images of chairs.  Regardless of what you name your data structures, if you use an Image type, and don’t specify a set of images, this set of chair images will always be used.  No magic, just a tricky demo.

To change the images to something more appropriate to your project, you can re-open the definition for the Image property that I created, and specify a folder on your computer.  When you do this, you’ll end up with sample values that look more like this (assuming you used the same images I did.)

SNAGHTML27b15a01

Now it’s time to actually use this data.

Using Sample Data in a Windows Phone App

First, even though this is called “Sample Data"," if you have a small set of static data that you’re intending to use in your application, there’s absolutely nothing wrong with making this a permanent part of your application.  That being said, in order to get this data into our ListBox that we created much earlier in this article, you can simply drag the “Chairs” node from the Data tab directly into your Listbox control, like this (the blue box is my mouse dragging the data to the ListBox…click to enlarge):

image

The moment you let go of your data, it will immediately create two things for you:

  • An DataTemplate for laying out the individual elements in the ListBox.
  • A binding between the SampleData and your ListBox.

In this example, the DataTemplate is stored directly in our MainPage.xaml page, and looks like this:

<DataTemplate x:Key="ChairsItemTemplate">
    <StackPanel>
        <TextBlock Text="{Binding Description}"/>
        <Image Source="{Binding Image}" HorizontalAlignment="Left" Height="64" Width="64"/>
        <TextBlock Text="{Binding Price}"/>
        <TextBlock Text="{Binding SKU}"/>
    </StackPanel>
</DataTemplate> 

You will see that our ListBox contains an ItemTemplate binding to this DataTemplate, and the ItemsSource is defined as our Chairs data:

<ListBox Margin="8,8,0,8" ItemTemplate="{StaticResource ChairsItemTemplate}" ItemsSource="{Binding Chairs}"/> 

In order to edit how the DataTemplate appears, we can use Expression Blend to do this too.  Right-click on your ListBox in Expression Blend, and choose

Edit Additional Templates > Edit Generated Items (ItemTemplate) > Edit Current

image

By doing this, you should notice that several things in our interface have changed.  First, at the top of our design pane, it now indicates that we’re working on our ListBox’s ItemTemplate.

image

Second, take a look at your Objects and Timeline panel.  It is now specifically focused on the contents of the ItemTemplate, which contains 3 TextBlocks and an Image control.

image

We can also now manipulate the elements of our ItemTemplate directly on the design surface.  For example, I just made the first image larger.  Since we are editing the template, you’ll notice that all of the images also got larger.

image

In the next image, you’ll notice that I moved the Description TextBlock to the bottom of the template, and right aligned all of the TextBlocks.  The Price has also had its font size increased, and the foreground color is now green.

image

At this point, unless you have a need to make this prettier, you have a working application.  Running it in the emulator will result in an application that has a scrolling ListBox.  This is how it appears, based on the changes I have made:

image

Where Is All Of This Data Stored?

Since we can deploy this application to the emulator, and the data appears, and we can use and manipulate it, you might be wondering just how this is stored in our application, and how it works.

If you take a look at your project structure, you should notice a new folder named SampleData.

image

Inside this folder, you’ve got a Furniture.xaml file which contains your actual generated data. Its contents look like this:

<!--
      *********    DO NOT MODIFY THIS FILE     *********
      This file is regenerated by a design tool. Making
      changes to this file can cause errors.
-->
<SampleData:Furniture xmlns:SampleData="clr-namespace:Expression.Blend.SampleData.Furniture" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <SampleData:Furniture.Chairs>
    <SampleData:ChairsItem SKU="366413" Price="$100" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day1-EmulatorTools.png" Description="Nam aliquam sed dis cras class duis integer maecenas praesent" />
    <SampleData:ChairsItem SKU="420965" Price="$29.99" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day10-NetworkInformation.png" Description="Accumsan aenean quisque bibendum mauris curae nullam donec vivamus est aliquam" />
    <SampleData:ChairsItem SKU="727463" Price="$249.99" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day11-LiveTiles.png" Description="Nunc aliquet blandit aptent auctor hac congue dictumst eleifend amet etiam ante fusce leo commodo facilisi cursus conubia dictum" />
    <SampleData:ChairsItem SKU="549249" Price="$1000" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day12-BetaTesting.png" Description="Lectus cubilia libero arcu dapibus lorem mus faucibus diam habitant egestas" />
    <SampleData:ChairsItem SKU="829031" Price="$2.99" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day13-MarketplaceTestKit.png" Description="Euismod inceptos nec eget interdum non elit morbi feugiat nulla ligula gravida lobortis iaculis litora" />
    <SampleData:ChairsItem SKU="758558" Price="$300" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day14-OData.png" Description="Proin enim lacinia laoreet augue nascetur natoque erat dolor per posuere" />
    <SampleData:ChairsItem SKU="342996" Price="$10,999" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day15-ProgressBar.png" Description="Fames sed sem felis sit eros vel nam ipsum justo sed nibh" />
    <SampleData:ChairsItem SKU="604077" Price="$49.99" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day16-IsolatedStorageExplorer.png" Description="Nisi potenti pretium dis pharetra nisl placerat pulvinar luctus lacus est hac sagittis nunc lorem magnis rhoncus leo sodales" />
    <SampleData:ChairsItem SKU="673946" Price="$25.34" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day17-LocalDatabase.png" Description="Viverra odio orci mattis mus magna massa pede quam aliquam senectus metus nec morbi" />
    <SampleData:ChairsItem SKU="177653" Price="$100" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day17-WindowsAzure.png" Description="Non mauris sociosqu integer suscipit quisque torquent mollis quis per ultrices vehicula sed neque" />
    <SampleData:ChairsItem SKU="788040" Price="$100" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day18-ExpressionBlendSampleData.png" Description="Aenean nam cras maecenas duis class nunc aliquam sed amet praesent dis mauris" />
    <SampleData:ChairsItem SKU="547641" Price="$100" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day19-AddingTiltEffects.png" Description="Integer ante arcu diam accumsan bibendum est nullam dictumst eleifend curae aptent eget donec quisque elit facilisi faucibus" />
    <SampleData:ChairsItem SKU="401054" Price="$29.99" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day2-DeviceStatus.png" Description="Enim habitant vivamus auctor etiam fusce congue aliquam erat inceptos" />
    <SampleData:ChairsItem SKU="256092" Price="$249.99" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day20-Ringtones.png" Description="Interdum lobortis aliquet blandit commodo hac conubia lorem cubilia leo nascetur eros pharetra cursus" />
    <SampleData:ChairsItem SKU="852495" Price="$1000" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day21-Sockets.png" Description="Dapibus nibh placerat nisi mus nec morbi nulla nisl proin egestas non euismod" />
    <SampleData:ChairsItem SKU="657020" Price="$2.99" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day22-AppConnect.png" Description="Per pulvinar feugiat dictum sed gravida sem iaculis sagittis sit lectus lacinia nunc laoreet odio" />
    <SampleData:ChairsItem SKU="450567" Price="$300" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day23-ExecutionModel.png" Description="Augue senectus vel nam sed orci sociosqu dis libero dolor natoque pede ligula fames posuere felis est potenti quam" />
    <SampleData:ChairsItem SKU="546952" Price="$10,999" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day24-ProfilerTool.png" Description="Litora luctus hac ipsum suscipit magnis torquent pretium rhoncus leo quis justo sodales urna mus ultrices lacus lorem viverra nec" />
    <SampleData:ChairsItem SKU="481783" Price="$49.99" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day25-BackgroundAgents.png" Description="Mattis cras aliquam duis nunc amet magna mauris massa ante integer mollis non per sed quisque" />
    <SampleData:ChairsItem SKU="200702" Price="$25.34" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day26-BackgroundFileTransfers.png" Description="Metus morbi sem neque sit netus vel nam arcu vehicula sed volutpat nulla porta diam" />
    <SampleData:ChairsItem SKU="536695" Price="$100" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day27-MicrophoneAPI.png" Description="Dis purus montes vivamus eget maecenas aliquam elit nostra est risus velit" />
    <SampleData:ChairsItem SKU="275101" Price="$29.99" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day28-MediaLibrary.png" Description="Ornare vitae platea class aliquet hac curae primis praesent enim erat accumsan leo eros blandit bibendum donec nibh rutrum mus" />
    <SampleData:ChairsItem SKU="979319" Price="$249.99" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day29-Globalization.png" Description="Nec dictumst commodo nisi etiam nisl eleifend conubia cubilia nunc sapien fusce dapibus non semper sociis egestas" />
    <SampleData:ChairsItem SKU="234379" Price="$1000" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day3-Reminders.png" Description="Taciti odio euismod facilisi faucibus lorem habitant per tellus tempor sed orci inceptos feugiat pede morbi quam" />
    <SampleData:ChairsItem SKU="248085" Price="$2.99" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day30-ConnectionSettings.png" Description="Nulla tempus tortor proin interdum augue quis gravida iaculis lacinia turpis lobortis urna sem varius sit cras laoreet vel" />
    <SampleData:ChairsItem SKU="982403" Price="$300" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day31-PromotingYourApplication.png" Description="Nascetur nam sed aenean pharetra dis natoque posuere potenti mauris pretium dolor fames placerat nullam aptent" />
    <SampleData:ChairsItem SKU="106433" Price="$10,999" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day4-Compass.png" Description="Est pulvinar duis rhoncus sodales felis nunc hac viverra amet ante ipsum auctor congue" />
    <SampleData:ChairsItem SKU="203433" Price="$49.99" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day5-Gyroscope.png" Description="Leo cursus mus arcu dictum nec diam sagittis aliquam eget non integer lectus elit per enim erat senectus" />
    <SampleData:ChairsItem SKU="660918" Price="$25.34" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day6-Motion.png" Description="Libero justo ligula sed sociosqu sem eros lacus suscipit sit torquent litora quisque nibh nisi nisl lorem" />
    <SampleData:ChairsItem SKU="734363" Price="$100" Image="/Day18_BlendSampleData;component/SampleData/Furniture/Furniture_Files/Day7-RawCamera.png" Description="Nunc magna vel massa luctus odio nam orci ultrices vivamus sed" />
  </SampleData:Furniture.Chairs>
</SampleData:Furniture> 

The actual structure of the data in this file is defined by the Furniture.xaml.cs file, which contains the classes and properties that we defined when we first created our Sample Data.  You can see that each of the properties are shown here, as well as references to the location of our sample images.

//      *********    DO NOT MODIFY THIS FILE     *********
//      This file is regenerated by a design tool. Making
//      changes to this file can cause errors.
namespace Expression.Blend.SampleData.Furniture
{
    using System;

// To significantly reduce the sample data footprint in your production application, you can set
// the DISABLE_SAMPLE_DATA conditional compilation constant and disable sample data at runtime.
#if DISABLE_SAMPLE_DATA
    internal class Furniture { }
#else

    public class Furniture : System.ComponentModel.INotifyPropertyChanged
    {
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }

        public Furniture()
        {
            try
            {
                System.Uri resourceUri = new System.Uri("/Day18_BlendSampleData;component/SampleData/Furniture/Furniture.xaml", System.UriKind.Relative);
                if (System.Windows.Application.GetResourceStream(resourceUri) != null)
                {
                    System.Windows.Application.LoadComponent(this, resourceUri);
                }
            }
            catch (System.Exception)
            {
            }
        }

        private Chairs _Chairs = new Chairs();

        public Chairs Chairs
        {
            get
            {
                return this._Chairs;
            }
        }
    }

    public class ChairsItem : System.ComponentModel.INotifyPropertyChanged
    {
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }

        private double _SKU = 0;

        public double SKU
        {
            get
            {
                return this._SKU;
            }

            set
            {
                if (this._SKU != value)
                {
                    this._SKU = value;
                    this.OnPropertyChanged("SKU");
                }
            }
        }

        private string _Price = string.Empty;

        public string Price
        {
            get
            {
                return this._Price;
            }

            set
            {
                if (this._Price != value)
                {
                    this._Price = value;
                    this.OnPropertyChanged("Price");
                }
            }
        }

        private System.Windows.Media.ImageSource _Image = null;

        public System.Windows.Media.ImageSource Image
        {
            get
            {
                return this._Image;
            }

            set
            {
                if (this._Image != value)
                {
                    this._Image = value;
                    this.OnPropertyChanged("Image");
                }
            }
        }

        private string _Description = string.Empty;

        public string Description
        {
            get
            {
                return this._Description;
            }

            set
            {
                if (this._Description != value)
                {
                    this._Description = value;
                    this.OnPropertyChanged("Description");
                }
            }
        }
    }

    public class Chairs : System.Collections.ObjectModel.ObservableCollection<ChairsItem>
    {
    }
#endif
} 

Finally, you have the Furniture_Files folder, which contains all of the actual sample images that we’re using.  Because we used both the default chair images, as well as my own collection, you’ll find that each of the images is inside this folder for you.  As the comments show, if you’re planning on editing this Sample Data from Expression Blend again, don’t do it.  Your changes will be discarded.  These are generated code files, and should be treated as such.

Summary

So, there you have it.  You have an application that uses Sample Data that you created in Expression Blend to populate a ListBox, using a DataTemplate.  There are many places where you might find this technique handy, so keep it in mind for static data sets rather than using something more complicated like a database or web service.

If you would like to download this entire working Windows Phone application that uses this Sample Data, click the Download Code button below:

download

Tomorrow, Doug Mair is back to discuss adding Tilt Effects to your XAML elements, giving some interaction to your user’s touch gestures.  See you then!

toolsbutton



Source: http://www.jeffblankenburg.com/2011/11/18/31-days-of-mango-day-18-using-sample-data/

The Mobile Zone is brought to you in partnership with Strongloop and IBM.  Visually compose APIs with easy-to-use tooling. Learn how IBM API Connect provides near-universal access to data and services both on-premises and in the cloud.

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}