Archives

Archives / 2011 / May
  • The Basics of MVVM in WPF

    This is a follow-up to my previous blog post on the Basics of MVVM in which I used Silverlight to illustrate how to use a basic MVVM design. I had so many emails asking for a WPF version, I decided to post this sample using WPF.

    Load a WPF List Box without MVVM

    To start, let's write code to load a list box control in WPF without using the MVVM design pattern. Create a new WPF project and add a User Control named ucNoMVVM to this project. Add a ListBox control to the user control and set the Name property to lstData. Add a Loaded event procedure to the XAML so it will create a Window_Loaded event procedure.

    <UserControl ...
      Loaded="UserControl_Loaded">

    The sample project that comes with this posting (see the end of this blog for instructions on download) uses a Product table in a database to load data in the UserControl_Loaded event procedure.

    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
      GetProducts();
    }

    private void GetProducts()
    {
      Products coll = new Products();
      string sql = string.Empty;
      SqlDataAdapter da = null;
      DataTable dt = new DataTable();

      sql = "SELECT ProductName ";
      sql += " FROM Product ";

      // Create Data Adapter
      da = new SqlDataAdapter(sql,
        ConfigurationManager.
              ConnectionStrings["ConnectString"].
                ConnectionString);
      // Fill DataTable with Products
      da.Fill(dt);

      // Loop thru all rows
      // Create a new Product object each time thru
      foreach (DataRow dr in dt.Rows)
      {
        Product prod = new Product();

        prod.ProductName =
          Convert.ToString(dr["ProductName"]);

        coll.Add(prod);
      }

      // Fill in ListBox
      lstData.DataContext = coll;
    }

    The code in the GetProducts method is fairly straight forward ADO.NET code to retrieve data from a Product table, create a DataTable and loop through each row of the DataTable to create a new Product object. Each Product object is added to a Products collection and when all rows have been loaded, that collection of product objects is assigned to the DataContext property of the list box named lstData.

    In the XAML of the list box you set the ItemsSource property to {Binding}. This tells the list box that you will be binding the data at runtime by setting the DataContext property. You also fill in the DisplayMemberPath property with a property of the Product object that you wish to be displayed in each row of the list box. In this case you are using the ProductName property.

    <ListBox ItemsSource="{Binding}"
             DisplayMemberPath="ProductName"
             Name="lstData" />

    That is all there is to writing the code behind and having it load data from a Product table. The problem with the above code is in order to test this code someone has to actually run the program and verify that this code works as it is supposed to. If you make a change to the database or to the UI you will then need to have someone run the application again to ensure it still works. You have to repeat this testing each time a change is made. This becomes very tedious and time consuming for the developer and the tester.

    Load a List Box using MVVM in WPF

    To take the previous sample and convert it into an MVVM design pattern, you simply need to create a class for your WPF User Control to bind to. This class, called ProductViewModel creates a public method named GetProducts. In addition a public property called DataCollection is created. In the "set" of this property you will raise a PropertyChanged event to inform the ListBox control that will be bound to this property to refresh its data by calling the "get" procedure in this property.

    I will let you look up the implementation of the PropertyChanged event procedure in the sample code that you download for this posting. Other than that, the complete View Model class is shown in the list below:

    public class ProductViewModel : INotifyPropertyChanged
    {
      #region INotifyPropertyChanged
      /// <summary>
      /// The PropertyChanged Event to raise to any UI object
      /// </summary>
      #endregion

      private Products _DataCollection;

      public Products DataCollection
      {
        get { return _DataCollection; }
        set
        {
          _DataCollection = value;
          RaisePropertyChanged("DataCollection");
        }
      }

      public void GetProducts()
      {
        Products coll = new Products();
        string sql = string.Empty;
        SqlDataAdapter da = null;
        DataTable dt = new DataTable();

        sql = "SELECT ProductName ";
        sql += " FROM Product ";

        // Create Data Adapter
        da = new SqlDataAdapter(sql,
          ConfigurationManager.
                ConnectionStrings["ConnectString"].
                  ConnectionString);
        // Fill DataTable with Products
        da.Fill(dt);

        // Loop thru all rows
        // Create a new Product object each time thru
        foreach (DataRow dr in dt.Rows)
        {
          Product prod = new Product();

          prod.ProductName =
            Convert.ToString(dr["ProductName"]);

          coll.Add(prod);
        }

        // Assign to DataCollection property to
        // raise PropertyChanged event
        DataCollection = coll;
      }
    }

    The above class is not that much more code than you wrote in the code behind. In fact, the implementation of the PropertyChanged event can be put into a base class that all your view models inherit from. This will avoid duplicating this code in each view model class.

    Bind ProductViewModel Class to XAML

    Once you have the ProductViewModel class created; you now bind your User Control to this class. Any WPF user control (or Window) may create an instance of any class in your application within XAML. First you create an XML namespace as shown by the arrow next to "Callout 1" in Figure 1.

    Figure

    Figure 1: XAML can create an instance of a class in the UserControl.Resources section of your user control.

    The XML namespace is given an alias and references a .NET namespace from your WPF application. In this XAML the alias for the namespace is called "vm". Next, you create a UserControl.Resources section in the XAML and using an XML element you specify the XML namespace followed a colon and then by the class name you wish to instantiate as shown by "Callout 2" in Figure 1.

    The following line of code in the XAML is what creates an instance of the ProductViewModel class and assigns it to the static resource variable name listed in the x:Key attribute.

    <vm:ProductViewModel x:Key="viewModel" />

    The above line is the equivalent of the following in .NET:

    using vm = WPF_MVVM_Easy;

    vm.ProductViewModel viewModel = new vm.ProductViewModel();

    Bind the instance of this class to the list box control you created on your WPF user control using the standard {Binding} syntax as shown in Figure 2.

    Figure 2

    Figure 2: Bind the ListBox to the resource you created

    In the ItemsSource of the list box you specify the source of the data as coming from the instance of the ProductViewModel class you created in the resources section. The Path property in the Binding specifies the property in the class you wish to get the collection of data from. In this case the name of the property in the ProductViewModel class is called DataCollection (Figure 3).

    Figure 3

    Figure 3: The Path attribute refers to the property where the data is coming from in the class to which this UI object is bound

    Write the Code Behind

    In your User Control you still need the UserControl_Loaded event procedure just like you did when you were not using the MVVM design pattern. The only difference is you will only have one line of code to call the GetProducts() method in the ProductViewModel class.

    Since the XAML created the ProductViewModel class you need to get a reference to that specific instance so you can use it in the code behind. In the constructor you will use the Resources collection to access the x:Key you assigned to the view model. In this case the key name is "viewModel". So you access the resources on this user control using this.Resources["viewModel"] and casting the result as a ProductViewModel class and putting it into a field variable on this user control called _ViewModel. You can now call any method or access any property in the ProductViewModel class through this field.

    public partial class ucMVVM : UserControl
    {
      ProductViewModel _ViewModel;

      public ucMVVM()
      {
        InitializeComponent();

        _ViewModel = (ProductViewModel)this.Resources["viewModel"];
      }

      private void UserControl_Loaded(object sender, RoutedEventArgs e)
      {
        _ViewModel.LoadAll();
      }
    }

    That is all there is to migrating your code into an MVVM design pattern. The primary advantage of this design pattern is you can now write a unit test to test the view model class. You do not need to have a tester run the application in order to verify that everything worked. In addition you also now have a view model class that you can reuse in a ASP.NET or Windows Forms application.

    Summary

    Hopefully this post helped you see how easy it is to move code from the code behind of your user interface and put it into a class. That is the whole key to MVVM; simply moving code into a class. Do not worry about being 100% "code behind free". That is an almost impossible goal and most often requires you to write more code! That is certainly not a good thing. If your event procedures in your UI are simply doing UI code or making a single call to a method in your View Model, then you have accomplished the goals of MVVM; namely reusability, maintainability and testability. You also get one more benefit; having event procedures in your UI makes it easier to follow the flow of the application.

    NOTE: You can download this article and many samples like the one shown in this blog entry at my website. http://www.pdsa.com/downloads. Select "Tips and Tricks", then "The Basics of MVVM in WPF" from the drop down list.

    Good Luck with your Coding,
    Paul Sheriff

    ** SPECIAL OFFER FOR MY BLOG READERS **
    We frequently offer a FREE gift for readers of my blog. Visit http://www.pdsa.com/Event/Blog for your FREE gift!

    Read more...

  • The Basics of MVVM

    While training and consulting with clients around the country, I find that many developers still have trouble grasping the concept of Model-View-View Model (MVVM) as used in Silverlight or WPF. In this blog post I thought I would show two examples side-by-side to help you learn how to move from the more traditional model of development to MVVM.

    Why use MVVM

    The reasons why programmers are adopting MVVM or the Model View Controller (MVC) design patterns are the same reasons why programmers adopted Object Oriented Programming (OOP) almost 30 years ago: reusability, maintainability and testability. Wrapping the logic of your application into classes allows you to reuse those classes in many different applications. Maintaining logic in classes allows you to fix any bugs in just one place and any other classes using that class automatically get the fix. When you don’t use global variables in an application, testing your application becomes much simpler. Wrapping all variables and logic that operates upon those variables into one class allows you to create a set of tests to check each property and method in the class quickly and easily.

    The thing to remember with MVVM and MVC is all you are doing is moving more of the logic out of the User Interface (UI) and into a class that simply has properties and methods that you will bind to the user interface. One example of the type of logic you move into a class is setting the DataContext property of a list box (in Silverlight/WPF) when you want to display a collection of objects in that list box control. Instead of setting the DataContext property directly you simply set a property in the class where you load that collection of objects. If you bind this property to the list box control then the list box will automatically redraw itself when this property changes.

    To use MVVM you must be using classes and not just writing all your code in the code behind of your UI. For VB.NET programmers this also means you are NOT using modules. The whole key to MVVM or MVC is the use of classes with properties and methods that mimic the behavior you want in the UI. This means setting properties that are bound to UI controls and calling methods when you want to perform some action that you would normally write in the Click event of a button.

    Load a List Box without MVVM

    To start, let’s write code to load a list box control in Silverlight without using the MVVM design pattern. Create a new Silverlight project and to the MainPage.xaml add a ListBox control to the page and set the Name property to lstData. Add a Loaded event procedure to the XAML so it will create a UserControl_Loaded event procedure.

    <UserControl ...
      Loaded="UserControl_Loaded">

    The sample project that comes with this posting (see the end of this blog for instructions on download) has a WCF service that will return a collection of Product objects. In the UserControl_Loaded event procedure you write code to load the Project data and give that data to the list box.

    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
      ProductServiceClient client = new ProductServiceClient();

      client.GetProductsCompleted += new
          EventHandler<GetProductsCompletedEventArgs>
             (client_GetProductsCompleted);
      client.GetProductsAsync();
      client.CloseAsync();
    }

    void client_GetProductsCompleted(object sender,
      GetProductsCompletedEventArgs e)
    {
      lstData.DataContext = e.Result;
    }

    The code in the Loaded event procedure instantiates a generated WCF service client object called ProductServiceClient. Next it hooks up the GetProductsCompleted event procedure that is called when the asynchronous call to the GetProductsAsync() method is complete. In the GetProductsCompleted event procedure you take the e.Result property and give it to the DataContext property of the list box called lstData.

    In the list box named lstData you need to set the ItemsSource property to {Binding}. This tells the list box that you will be binding the data at runtime by setting the DataContext property. You also fill in the DisplayMemberPath property with a property of the Product object that you wish to be displayed in each row of the list box. In this case you are using the ProductName property.

    <ListBox ItemsSource="{Binding}"
             DisplayMemberPath="ProductName"
             Name="lstData" />

    That is all there is to writing the code behind and having it load data from a Product WCF service. The problem with the above code is in order to test this code someone has to actually run the program and verify that this code works as it is supposed to. If you make a change to the service or to the UI you will then need to have someone run the application again to ensure it still works. You have to repeat this testing each time a change is made. This becomes very tedious and time consuming for the developer and the tester.

    Load a List Box using MVVM

    To take the previous sample and convert it into an MVVM design pattern, you simply need to create a class for your Silverlight user control to bind to. This class, called ProductViewModel recreates the UserControl_Loaded event procedure and the GetProductsCompleted event procedure as the LoadAll method in the class and the GetProductsCompleted event procedure.

    When the data is returned from the WCF service in the GetProductsCompleted event, that data is placed into a property called DataCollection as opposed to setting the DataContext property of a list box directly. This property is of the type ObservableCollection<Product>. The only thing unique about this property is in the “set” procedure; you not only set the value to the _DataCollection field, you also call a method named RaisePropertyChanged. This method raises the PropertyChanged event procedure. This is a standard event in XAML whose sole job is to inform any UI elements bound to this property that they should call the “get” procedure because the data has just been updated.

    I will let you look up the implementation of the PropertyChanged event procedure in the sample code that you download for this posting. Other than that, the complete View Model class is shown in the list below:

    public class ProductViewModel : INotifyPropertyChanged
    {
      #region INotifyPropertyChanged
      /// <summary>
      /// The PropertyChanged Event Informs the UI
      /// when a Property in this class changes
      /// </summary>
      /// IMPLEMENTATION GOES HERE
      #endregion

      private ObservableCollection<Product> _DataCollection;

      public ObservableCollection<Product> DataCollection
      {
        get { return _DataCollection; }
        set
        {
          _DataCollection = value;
          RaisePropertyChanged("DataCollection");
        }
      }

      public void LoadAll()
      {
        ProductServiceClient client = new ProductServiceClient();

        client.GetProductsCompleted += new
          EventHandler<GetProductsCompletedEventArgs>
           (client_GetProductsCompleted);
        client.GetProductsAsync();
        client.CloseAsync();
      }

      void client_GetProductsCompleted(object sender,
       GetProductsCompletedEventArgs e)
      {
        DataCollection = e.Result;
      }
    }

    The above class is not that much more code that you wrote in the code behind. In fact, the implementation of the PropertyChanged event can be put into a base class that all your view models inherit from. This will avoid duplicating this code in each view model class.

    Bind ProductViewModel Class to XAML

    Once you have the ProductViewModel class created; you now bind your User Control to this class. Any Silverlight user control may create an instance of any class in your application within XAML. First you create an XML namespace as shown by the arrow next to “Callout 1” in Figure 1.

    Figure 1
    Figure 1: XAML can create an instance of a class in the UserControl.Resources section of your user control.

    The XML namespace is given an alias and references a .NET namespace from your Silverlight application. In this XAML the alias for the namespace is called “vm”. Next, you create a UserControl.Resources section in the XAML and using an XML element you specify the XML namespace followed a colon and then by the class name you wish to instantiate as shown by “Callout 2” in Figure 1.

    The following line of code in the XAML is what creates an instance of the ProductViewModel class and assigns it to the static resource variable name listed in the x:Key attribute.

    <vm:ProductViewModel x:Key="viewModel" />

    The above line is the equivalent of the following in .NET:

    using vm = SL_MVVM_Easy;

    vm.ProductViewModel viewModel = new vm.ProductViewModel();

    Bind the instance of this class to the list box control you created on your Silverlight user control using the standard {Binding} syntax as shown in Figure 2.

    Figure 2
    Figure 2: Bind the ListBox to the resource you created

    In the ItemsSource of the list box you specify the source of the data as coming from the instance of the ProductViewModel class you created in the resources section. The Path property in the Binding specifies the property in the class you wish to get the collection of data from. In this case the name of the property in the ProductViewModel class is called DataCollection (Figure 3).

    Figure 3
    Figure 3: The Path attribute refers to the property where the data is coming from in the class to which this UI object is bound

    Write the Code Behind

    In your User Control you still need the UserControl_Loaded event procedure just like you did when you were not using the MVVM design pattern. The only difference is you will only have one line of code to call the LoadAll() method in the ProductViewModel class.

    Since the XAML created the ProductViewModel class you need to get a reference to that specific instance so you can use it in the code behind. In the constructor you will use the Resources collection to access the x:Key you assigned to the view model. In this case the key name is “viewModel”. So you access the resources on this page using this.Resources[“viewModel”] and casting the result as a ProductViewModel class and putting it into a field variable on this user control called _ViewModel. You can now call any method or access any property in the ProductViewModel class through this field.

    public partial class ucMVVM : UserControl
    {
      ProductViewModel _ViewModel;

      public ucMVVM()
      {
        InitializeComponent();

        _ViewModel = (ProductViewModel)this.Resources["viewModel"];
      }

      private void UserControl_Loaded(object sender,
       System.Windows.RoutedEventArgs e)
      {
        _ViewModel.LoadAll();
      }
    }

    That is all there is to migrating your code into an MVVM design pattern. The primary advantage of this design pattern is you can now write a unit test to test the view model class. You do not need to have a tester run the application in order to verify that everything worked. In addition you also now have a view model class that you can reuse in a WPF or Windows Phone application. You could even reuse this view model class in an ASP.NET application.

    Summary

    Hopefully this post helped you see how easy it is to move code from the code behind of your user interface and put it into a class. That is the whole key to MVVM; simply moving code into a class. Do not worry about being 100% “code behind free”. That is an almost impossible goal and most often requires you to write more code! That is certainly not a good thing. If your event procedures in your UI are simply doing UI code or making a single call to a method in your View Model, then you have accomplished the goals of MVVM; namely reusability, maintainability and testability. You also get one more benefit; having event procedures in your UI makes it easier to follow the flow of the application.

    NOTE: You can download this article and many samples like the one shown in this blog entry at my website. http://www.pdsa.com/downloads. Select “Tips and Tricks”, then “The Basics of MVVM” from the drop down list.

    Good Luck with your Coding,
    Paul Sheriff

    ** SPECIAL OFFER FOR MY BLOG READERS **
    We frequently offer a FREE gift for readers of my blog. Visit http://www.pdsa.com/Event/Blog for your FREE gift!

    Read more...

  • Windows Phone Choosers

    Windows Phone does not yet support multi-tasking, however you can interact with some of the built-in applications on the phone from within your application. Depending on the application you call, you will either launch the application and pass in some data to the application, or you will launch the application and have some data returned. The former is called a launcher, while the later is called a chooser. In this blog post you will learn to call a chooser from your application and have that chooser return some data from the built-in application. The specific chooser for this blog post will be the PhoneNumberChooserTask as shown in Figure 1.

    Call the PhoneNumberChooserTask to return a phone number to your application.

    Figure 1: Call the PhoneNumberChooserTask to return a phone number to your application.

    Overview

    A Chooser on the Windows Phone application allows your application to call a built-in application to get some data from that application and return data. As an example, you might want to access the contacts on your phone and return a phone number to your application from one of those contacts. You can use the PhoneNumberChooserTask to have your application make a call to get that data. The data that is returned is specific to the task that you call. For a phone number, you will get a string that contains the phone number. For a photo chooser you would get back an IO stream that contains the image. You could then turn this into an image to display in your application.

    One important thing to keep in mind when using either of the launcher or chooser APIs is that calling these applications could cause your application to be tombstoned. It will be your responsibility to restore any data that you want after your application is reactivated from the tombstoned state.

    Calling a Chooser

    You may call any of the several built-in Chooser applications on the Windows Phone by simply using the classes contained in the Microsoft.Phone.Tasks namespace. The list of chooser classes are listed below:

    CameraCaptureTask
    EmailAddressChooserTask
    PhoneNumberChooserTask
    PhotoChooserTask
    SaveEmailAddressTask
    SavePhoneNumberTask

    Most of the names are pretty self-explanatory so you just need to figure out where you want to get the data that you need for your application. To use any of the Chooser task classes, you will first need to add a using statement at the top of your Page class.

    using Microsoft.Phone.Tasks;

    Next, you create a field in your Page class with a variable that will point to the specific chooser you wish to use.

    PhoneNumberChooserTask task = null;

    Now create an instance of the chooser class in the constructor for your page and hook up the “Completed” event.

    public ChooserPage()
    {
      InitializeComponent();

      // Need to create this here as your app could be tombstoned
      // Need to rehook the event for this chooser app
      task = new PhoneNumberChooserTask();
      task.Completed += new
          EventHandler<PhoneNumberResult>(task_Completed);
    }

    You must create the instance of the task and hook up Completed event handler in the constructor because your application could be tombstoned once it calls the choose application. Upon reactivating your application the constructor will be called again and the completed event needs to be hooked back up so the chooser can call the event.

    NOTE:  Not all choosers are tombstoned. Some are just temporarily deactivated. However, you should program defensively and always assume that your application will be tombstoned.

    In the sample application shown in Figure 1 you will click on a button to invoke the Phone Number Chooser task using the Show() method. On the emulator there is a set of contacts that you will be able to select from so you can try this out even if you don’t have a real Windows Phone. Once you select a phone number from your contact list you will be returned to your application. To make the call to the Phone Number chooser call the Show() method of the task object in the button click event procedure as shown in the code below.

    private void Button_Click(object sender, RoutedEventArgs e)
    {
      // Show Phone Number Chooser
      // NOTE: This particular task does NOT necessarily
      // tombstone your app.
      task.Show();
    }

    In the Completed event you will want to check the e.TaskResult to see if the user actually selected a phone number from the chooser. If the user goes to the chooser, but immediately clicks on the back button, then the e.TaskResult will NOT be equal to OK. If the user clicks on one of the contacts, then the chooser application will immediately end and the phone number will be returned. In this case the e.TaskResult will be set to OK and you can access the e.PhoneNumber property to place the phone number into the text box in your application.

    void task_Completed(object sender, PhoneNumberResult e)
    {
      // See if task completed
      if (e.TaskResult == TaskResult.OK)
        txtPhone.Text = e.PhoneNumber;  // Grab phone number
    }

    Summary

    In this blog post you were introduced to the Choosers that are available in the Windows Phone. You learned how to call the PhoneNumberChooserTask to access the contact list and return a phone number to your application. Using the chooser APIs allows you to call many of the built-in applications on the Windows Phone. Each chooser will return different data depending on what each one does. All choosers will fire a completed event once they return control back to your application. Even though all choosers will not necessarily tombstone your application, be sure to program for tombstoning just to be on the safe side.

    NOTE: You can download this article and many samples like the one shown in this blog entry at my website. http://www.pdsa.com/downloads. Select “Tips and Tricks”, then “Windows Phone Choosers” from the drop down list.

    Good Luck with your Coding,
    Paul Sheriff

    ** SPECIAL OFFER FOR MY BLOG READERS **
    We frequently offer a FREE gift for readers of my blog. Visit http://www.pdsa.com/Event/Blog for your FREE gift!

    Read more...

  • Windows Phone Launchers

    The Windows Phone does not support multi-tasking (yet), however you can call many of the built-in applications on the phone from your application. Depending on the application you call, you will either launch the application and pass in some data to the application, or you will launch the application and have some data returned. The former is called a launcher, while the later is called a chooser. In this blog post you will learn to call a launcher from your application. The specific launcher will be the SavePhoneNumberTask as shown in Figure 1.

    Read more...

  • From Zero to Silverlight in 1 Day!

    Hi All,

    Arranged by my fellow Microsoft Regional Director (www.TheRegion.com), Bill Wagner, I will be presenting a day long Silverligh event in Ann Arbor, MI on June 7th, 2011! I hope you will join us for this great 1 day event. The cost is only $100 (early-bird) and $125 regular price for a day of Silverlight training.

    Here is some more information about the event.

    From Zero to Silverlight in 1 Day

    Confused about how to get started using Silverlight? Have you attended Silverlight seminars only to find out that they are doing all this graphics stuff and you need to write a business application? This seminar will focus on Silverlight for the business application programmer. You will learn to create real-world business applications using Styles, Resources, Data Binding, WCF Services and much more in this 1 day seminar.

    Agenda:

    The following topics will be presented in this 1 day journey where we assume you know nothing about Silverlight. Along the way you will become very comfortable with the techniques you will need to know to create business applications.

    • Continental Breakfast (8:00am - 8:45 am)
    • From Zero to Silverlight in 75 Minutes (8:30am – 9:45am)
    • Styles, Resources and Templates, Oh My! (10am – 11am)
    • Eliminate Code using Data Binding (11am – 12:30pm)
    • 10 Cool Ways to use the Silverlight ListBox (1:30pm – 2:45pm)
    • Simplify the MVVM Design Pattern (3pm – 4pm)
    • 10 Tips to Spice up Your Silverlight Apps (Even if you are not a designer!) (4pm – 5pm)

    To get more information: http://www.srtsolutions.com/events/silverlight-business-applications-training

    To Register: http://zero2silverlight.eventbrite.com/

    Hope to see you there!

    Paul

    Read more...

  • Using the Windows Phone Pivot Control

    The Windows Phone Pivot control is similar to a Tab control on Windows Forms, WPF or Silverlight. Each “tab” or PivotItem you create is like a separate little page where you can have whatever other XAML you need. In this short blog post I will show you how to create a set of PivotItem controls where each control (tab) will display a list box of photos. You will be able to take a set of your photos, drop them into this project and try out this sample right away. In Figure 1 you can see the sample application that you will create. I named it “My Life in Categories” and it has a list of “tabs” across the top. Each tab is a different year and in each year is a list box with a list of pictures from your life.

    Read more...

  • Using the Windows Phone Panorama Control

    The Windows Phone Panorama control makes creating a wrap-around list of items very quick and easy to accomplish. In this short blog post I will show you how to create a nice panorama of a collection of photos. You will be able to take a set of your photos, drop them into this project and try out this sample right away. In Figure 1 you can see the sample application that you will create. I named it “My Life in Panorama” and it simply shows a list of pictures from your life. In this picture I show me at the top of Kilimanjaro in 2004.

    Figure 1: My Life in Panorama Sample

    Figure 1: My Life in Panorama Sample

    Create the Panorama Page

    To start, open VS.NET 2010 and choose New Project. Click on the Silverlight for Windows Phone tab, then click on Windows Phone Application and set the name to WPPanoramaSample as shown in Figure 2. NOTE: For this particular sample, do NOT choose the “Windows Phone Panorama Application”. We just want to create a simple panorama page and not worry about all the data stuff.

    Figure 2: Create a new Silverlight Application

    Figure 2: Create a new Windows Phone Application

    Once VS.NET has your new project created, click on MainPage.xaml and delete this page. Right mouse click on the project and select Add | Add New Item… from the context menu. Select Windows Phone Panorama Page from the item list and set the Name to MainPage.xaml (Figure 3).

    Figure 3: Add a Panorama Page

    Figure 3: Add a Panorama Page

    Click the OK button and your new main page will be ready for you to start adding pictures to in the Panorama control.

    Locate the XAML for the Panorama control within this page; it will look like the following.

    <controls:Panorama Title="my application">
      <!--Panorama item one-->
      <controls:PanoramaItem Header="item1">
        <Grid />
      </controls:PanoramaItem>
      <!--Panorama item two-->
      <controls:PanoramaItem Header="item2">
        <Grid />
      </controls:PanoramaItem>
    </controls:Panorama>

    A Panorama control is located in the Microsoft.Phone.Controls.dll, so an assembly reference was added to your project. An xml namespace with an alias of “controls” was added to the MainPage.xaml. This is why there is a “controls:” prefix on the Panorama control you see in the XAML.

    Each Panorama control allows you to create a title that will be displayed across all items that make up your Panorama page. Go ahead and modify the Title property to “My Life in Panorama”.

    Add Pictures and PanoramaItem Controls

    You are now ready to start adding your own pictures to your project and to the panorama. The Panorama control is made up of one or many PanoramaItem controls. Within the content for each of these PanoramaItem controls you may put any XAML you want. For our purposes here you will replace the <Grid /> control with an <Image> control.

    First, you need to create an Images folder in this project. Then gather any amount of pictures from your life that wish to display and copy them into this \Images folder in the VS.NET project.

    Now, you are ready to take each picture and create 1 PanoramaItem control for each picture. Modify the XAML in the MainPage.xaml to look like the following. Replace my image file names with your image file names and modify the Header of each PanoramaItem controls with appropriate headers. Keep the headers short so they are not chopped off. I find less than 12 characters works best for the Header attribute.

    <controls:Panorama Title="My Life in Panorama">
      <controls:PanoramaItem Header="Me in 1963">
        <Image Source="Images/MeIn1963.jpg" />
      </controls:PanoramaItem>
      <controls:PanoramaItem Header="Me in 1967">
        <Image Source="Images/MeIn1967.jpg" />
      </controls:PanoramaItem>
      <controls:PanoramaItem Header="Me in 1971">
        <Image Source="Images/MeIn1971.jpg" />
      </controls:PanoramaItem>
    </controls:Panorama>

    After putting in your images go ahead and run your application and you will be able to pan through all your images both forward and backward. When you get to the beginning (or the end) you will see that the control simply continues around in a continuous loop.

    Summary

    A Panorama control is ideal for a mobile application when you don’t really care where the user starts or ends up while browsing the data. It is very simple to create a Panorama control and the various PanoramaItem controls that make this up. You could easily extend this control to read the list of images to display from an XML file, or from a WCF service. You could then create the PanoramaItem controls in C# or VB.NET and add them to the Panorama control on the fly at runtime.

    NOTE: You can download this article and many samples like the one shown in this blog entry at my website. http://www.pdsa.com/downloads. Select “Tips and Tricks”, then “Using the Windows Phone Panorama Control” from the drop down list.

    Good Luck with your Coding,
    Paul Sheriff

    ** SPECIAL OFFER FOR MY BLOG READERS **
    We frequently offer a FREE gift for readers of my blog. Visit http://www.pdsa.com/Event/Blog for your FREE gift!

    Read more...