This post will show you how to create a portable class library (PCL) to reuse logic across client applications.  We show how to reuse the model and view model in various Windows platforms in this post, and show how to reuse it within an Android application in the post Build Android Apps With Xamarin Using Portable Class Libraries.  We will look at how the newly announced Universal Apps fit into this picture in a subsequent post.

Background

My team built a solution to help jumpstart custom development projects that involve mobile workers, showing how to leverage Microsoft Azure as the center of gravity for everything.  We built apps using ASP.NET MVC, Windows Phone 8, Windows 8 Store Apps, and we even used Xamarin to build iOS and Android apps.  All of these clients talk to Web API endpoints hosted in Azure, are authenticated with Windows Azure Active Directory, and leverage various services such as Service Bus and Push Notifications. 

One of the challenges with building all of these apps is trying to avoid writing the same thing over and over, reusing logic when possible.  That’s where using portable class libraries provides a huge advantage.

The code samples are based off the MSDN article Using Portable Class Library with Model-View-View Model.  This post simply adds a few things on top of that sample, including demonstrations of different views that reference a PCL.

Portable Class Libraries

Like many of you, I haven’t spent much time doing client development over the past few years, I have been strictly doing web development, primarily with SharePoint.  A key concept you may not already be familiar with is that of a Portable Class Library (PCL).  From MSDN:

The .NET Framework Portable Class Library project type in Visual Studio helps you build cross-platform apps and libraries for Microsoft platforms quickly and easily.

Portable class libraries can help you reduce the time and costs of developing and testing code. Use this project type to write and build portable .NET Framework assemblies, and then reference those assemblies from apps that target multiple platforms such as Windows and Windows Phone.

[via http://msdn.microsoft.com/en-us/library/vstudio/gg597391(v=vs.100).aspx]

Each platform has the concept of a class library that provides the implementation for each type of platform.

image

If I’m creating an app for Windows 8.1 and an app for Windows Phone 8, I don’t want to have to write that code twice.  I’d rather write it once and reference it from each project.  That’s exactly what a PCL provides you.  This helps you to create a single library of code that is shared across multiple platforms.  Think about this for a second, because it’s pretty cool.  I can write a library of code that can be written once and referenced from my Windows Phone 8, Windows 8.1 app, or even an app written with Xamarin. 

image

When you create a PCL, you choose the targets for your library, which determines the baseline functionality that you want to apply across platforms.

image

This PCL can then be referenced from a project that targets .NET 4.5 for desktop apps, Windows 8 or Windows 8.1 store apps, Windows Phone apps for WP8 or WP8.1 that use Silverlight, or even Xamarin apps that target Android or iOS. 

Write the code once and reference it across multiple project types.  To demonstrate the power behind this model, I will show an example of a PCL that enables reuse of models, repositories, and view models.  The platform-specific implementation is implemented in the views for each platform, which results in nearly zero code in each platform implementation.  The project structure shows the library of reusable code and the three platform implementations that reuse this code.

image

Reusing Models

The easiest thing to reuse in a PCL library is the model.  That’s typically a class that provides property getters and setters that model the data that you want to use.  A simple example is a Customer class:

Code Snippet
  1. using System;
  2. using System.ComponentModel;
  3.  
  4. namespace ReusableLibrary
  5. {
  6.     public class Customer : INotifyPropertyChanged
  7.     {
  8.         public event PropertyChangedEventHandler PropertyChanged;
  9.  
  10.         private string _fullName;
  11.         private string _phone;
  12.  
  13.         public int CustomerID { get; set; }
  14.  
  15.         public string FullName
  16.         {
  17.             get
  18.             {
  19.                 return _fullName;
  20.             }
  21.             set
  22.             {
  23.                 _fullName = value;
  24.                 OnPropertyChanged("FullName");
  25.             }
  26.         }
  27.  
  28.         public string Phone
  29.         {
  30.             get
  31.             {
  32.                 return _phone;
  33.             }
  34.             set
  35.             {
  36.                 _phone = value;
  37.                 OnPropertyChanged("Phone");
  38.             }
  39.         }
  40.  
  41.         protected virtual void OnPropertyChanged(string propName)
  42.         {
  43.             if (PropertyChanged != null)
  44.             {
  45.                 PropertyChanged(this, new PropertyChangedEventArgs(propName));
  46.             }
  47.         }
  48.     }
  49. }

Notice that we can do more than just primitive types here, we can also use the INotifyPropertyChanged interface to notify when a property changes.  Also notice the reuse of the PropertyChangedEventArgs type that can be reused across all implementations. 

Reusing a Repository

This one gets a little harder.  Reusing a repository is completely possible so long as the types that you are using are common across all implementations.  As an example, we have a CustomerRepository class that initializes with a few items.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace ReusableLibrary
  6. {
  7.     public class CustomerRepository
  8.     {
  9.         private List<Customer> _customers;
  10.  
  11.         public CustomerRepository()
  12.         {
  13.             _customers = new List<Customer>
  14.             {
  15.                 new Customer(){ CustomerID = 1, FullName="Dana Birkby", Phone="394-555-0181"},
  16.                 new Customer(){ CustomerID = 2, FullName="Adriana Giorgi", Phone="117-555-0119"},
  17.                 new Customer(){ CustomerID = 3, FullName="Wei Yu", Phone="798-555-0118"}
  18.             };
  19.         }
  20.  
  21.         public List<Customer> GetCustomers()
  22.         {
  23.             return _customers;
  24.         }
  25.  
  26.         public void UpdateCustomer(Customer SelectedCustomer)
  27.         {
  28.             Customer customerToChange = _customers.Single(
  29.               c => c.CustomerID == SelectedCustomer.CustomerID);
  30.             customerToChange = SelectedCustomer;
  31.  
  32.         }
  33.     }
  34. }

Admittedly, this is a simplistic scenario that might not be applicable.  For instance, your repository class might need to grab data from a database, in which case the classes to do so might not be available on all platforms.  In this case, you might need to inject the platform-specific implementation into the repository, and each platform deals with the specifics of how to obtain the data.  For now, we’ll stick with our simple case of returning a list of customer objects.

Reusing ViewModels

Here’s where it gets really tricky.  Defining ViewModels can be difficult based on differences between platforms.  For instance, handling navigation can be different between platforms, even between Windows Phone 8 and Windows Store applications.  Handling those differences requires that you create those abstractions yourself.  For a simple example of reusing the ViewModels, we first define a base class.

Code Snippet
  1. using System;
  2. using System.ComponentModel;
  3.  
  4. namespace ReusableLibrary
  5. {
  6.     public abstract class ViewModelBase : INotifyPropertyChanged
  7.     {
  8.         public event PropertyChangedEventHandler PropertyChanged;
  9.  
  10.         protected virtual void OnPropertyChanged(string propName)
  11.         {
  12.             if (PropertyChanged != null)
  13.             {
  14.                 PropertyChanged(this, new PropertyChangedEventArgs(propName));
  15.             }
  16.         }
  17.     }
  18. }

This base class provides the base implementation for handling property changed events in the ViewModel.  The responsibility of the view model is to provide the glue between the view and the model, which is typically done through events and commands.  When a property is changed, we raise an event.  We also want to provide the ability for our view model to respond to commands, such as a button is being clicked.  We provide this through a command class called RelayCommand that implements the ICommand interface, which is typical when using MVVM.

Code Snippet
  1. using System;
  2. using System.Windows.Input;
  3.  
  4. namespace ReusableLibrary
  5. {
  6.     public class RelayCommand : ICommand
  7.     {
  8.         private readonly Action _handler;
  9.         private bool _isEnabled;
  10.  
  11.         public RelayCommand(Action handler)
  12.         {
  13.             _handler = handler;
  14.         }
  15.  
  16.         public bool IsEnabled
  17.         {
  18.             get { return _isEnabled; }
  19.             set
  20.             {
  21.                 if (value != _isEnabled)
  22.                 {
  23.                     _isEnabled = value;
  24.                     if (CanExecuteChanged != null)
  25.                     {
  26.                         CanExecuteChanged(this, EventArgs.Empty);
  27.                     }
  28.                 }
  29.             }
  30.         }
  31.  
  32.         public bool CanExecute(object parameter)
  33.         {
  34.             return IsEnabled;
  35.         }
  36.  
  37.         public event EventHandler CanExecuteChanged;
  38.  
  39.         public void Execute(object parameter)
  40.         {
  41.             _handler();
  42.         }
  43.     }
  44. }

We can then define a view model that derives from the base class that wires up the ICommand interface implementation.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ReusableLibrary
  8. {
  9.     public class CustomerViewModel : ViewModelBase
  10.     {
  11.         private List<Customer> _customers;
  12.         private Customer _currentCustomer;
  13.         private CustomerRepository _repository;
  14.  
  15.         public CustomerViewModel()
  16.         {
  17.             _repository = new CustomerRepository();
  18.             _customers = _repository.GetCustomers();
  19.  
  20.             WireCommands();
  21.         }
  22.  
  23.         private void WireCommands()
  24.         {
  25.             UpdateCustomerCommand = new RelayCommand(UpdateCustomer);
  26.         }
  27.  
  28.         public RelayCommand UpdateCustomerCommand
  29.         {
  30.             get;
  31.             private set;
  32.         }
  33.  
  34.         public List<Customer> Customers
  35.         {
  36.             get { return _customers; }
  37.             set { _customers = value; }
  38.         }
  39.  
  40.  
  41.         public Customer CurrentCustomer
  42.         {
  43.             get
  44.             {
  45.                 return _currentCustomer;
  46.             }
  47.  
  48.             set
  49.             {
  50.                 if (_currentCustomer != value)
  51.                 {
  52.                     _currentCustomer = value;
  53.                     OnPropertyChanged("CurrentCustomer");
  54.                     UpdateCustomerCommand.IsEnabled = true;
  55.                 }
  56.             }
  57.         }
  58.  
  59.         public void UpdateCustomer()
  60.         {
  61.             _repository.UpdateCustomer(CurrentCustomer);
  62.             OnPropertyChanged("CurrentCustomer");
  63.             UpdateCustomerCommand.IsEnabled = false;
  64.         }
  65.     }
  66.  
  67. }

Our view model can now respond to commands and notify any listeners when a property is changed.  This is all typical MVVM plumbing so far, but the key point is that this is all implemented within a single PCL library that can be reused across platforms.

Defining a View for WPF

OK, let’s start to show the payoff.  We can now create a WPF application that references the PCL library.

image

I generated a blank WPF application and then changed the MainWindow.xaml to bind to the library.

Code Snippet
  1. <Window x:Class="WPFApplication.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         xmlns:viewModels="clr-namespace:ReusableLibrary;assembly=ReusableLibrary"
  5.         Title="MainWindow"
  6.         Height="350"
  7.         Width="525">
  8.     <Window.Resources>
  9.         <viewModels:CustomerViewModel x:Key="ViewModel" />
  10.     </Window.Resources>
  11.     <Grid DataContext="{Binding Source={StaticResource ViewModel}}">
  12.         <Grid.ColumnDefinitions>
  13.             <ColumnDefinition></ColumnDefinition>
  14.             <ColumnDefinition></ColumnDefinition>
  15.         </Grid.ColumnDefinitions>
  16.         <Grid.RowDefinitions>
  17.             <RowDefinition Height="Auto"></RowDefinition>
  18.             <RowDefinition Height="Auto"></RowDefinition>
  19.             <RowDefinition Height="Auto"></RowDefinition>
  20.             <RowDefinition Height="Auto"></RowDefinition>
  21.             <RowDefinition Height="Auto"></RowDefinition>
  22.         </Grid.RowDefinitions>
  23.         <TextBlock Height="23"
  24.                    Margin="5"
  25.                    HorizontalAlignment="Right"
  26.                    Grid.Column="0"
  27.                    Grid.Row="0"
  28.                    Name="textBlock2"
  29.                    Text="Select a Customer:"
  30.                    VerticalAlignment="Top" />
  31.         <ComboBox Height="23"
  32.                   HorizontalAlignment="Left"
  33.                   Grid.Column="1"
  34.                   Grid.Row="0"
  35.                   Name="CustomersComboBox"
  36.                   VerticalAlignment="Top"
  37.                   Width="173"
  38.                   DisplayMemberPath="FullName"
  39.                   SelectedItem="{Binding Path=CurrentCustomer, Mode=TwoWay}"
  40.                   ItemsSource="{Binding Path=Customers}" />
  41.         <TextBlock Height="23"
  42.                    Margin="5"
  43.                    HorizontalAlignment="Right"
  44.                    Grid.Column="0"
  45.                    Grid.Row="1"
  46.                    Name="textBlock4"
  47.                    Text="Customer ID" />
  48.         <TextBlock Height="23"
  49.                    Margin="5"
  50.                    HorizontalAlignment="Right"
  51.                    Grid.Column="0"
  52.                    Grid.Row="2"
  53.                    Name="textBlock5"
  54.                    Text="Name" />
  55.         <TextBlock Height="23"
  56.                    Margin="5"
  57.                    HorizontalAlignment="Right"
  58.                    Grid.Column="0"
  59.                    Grid.Row="3"
  60.                    Name="textBlock9"
  61.                    Text="Phone" />
  62.         <TextBlock Height="23"
  63.                    HorizontalAlignment="Left"
  64.                    Grid.Column="1"
  65.                    Grid.Row="1"
  66.                    Name="CustomerIDTextBlock"
  67.                    Text="{Binding ElementName=CustomersComboBox, Path=SelectedItem.CustomerID}" />
  68.         <TextBox Height="23"
  69.                  HorizontalAlignment="Left"
  70.                  Grid.Column="1"
  71.                  Grid.Row="2"
  72.                  Width="219"
  73.                  Text="{Binding Path=CurrentCustomer.FullName, Mode=TwoWay}" />
  74.         <TextBox Height="23"
  75.                  HorizontalAlignment="Left"
  76.                  Grid.Column="1"
  77.                  Grid.Row="3"
  78.                  Width="219"
  79.                  Text="{Binding Path=CurrentCustomer.Phone, Mode=TwoWay}" />
  80.         <Button Name="UpdateButton"
  81.                 Command="{Binding UpdateCustomerCommand}"
  82.                 Content="Update"
  83.                 Height="40"
  84.                 Grid.Column="0"
  85.                 Grid.Row="4"
  86.                 VerticalAlignment="Top"
  87.                 HorizontalAlignment="Center"
  88.                 Width="80"
  89.                 Grid.ColumnSpan="2"
  90.                 Margin="10,10,10,10" />
  91.  
  92.     </Grid>
  93.  
  94. </Window>

I know all that XAML looks intimidating, but it looks like this when it runs.

image

What’s even better is the code-behind for the MainWindow.xaml page.  I offer it here in its entirety.

image

There’s no databinding code, no code for a button click event, there’s just the single call to InitializeComponent and that’s it.  The view is entirely in XAML, and the code provides two-way databinding to the view model, which in turn changes properties of the model. When the model is updated, it notifies the view of the change, and the view responds accordingly.  To demonstrate, I change the customer’s name to “Kirk Evans’ and click the update button, and the model is changed and reflected in the UI.

image

Still not seeing the payoff?  Let’s create a Windows Phone app.

Defining a View for Windows Phone

Now we’ll create a Windows Phone project that references our PCL. 

image

The Windows Phone 8 app contains a single page, MainPage.xaml.  First, let’s look at its code-behind.  I present the code-behind in its entirety.

image

I hope you get the point by now that there’s no button1_click, there’s no databinding code, all of that implementation is contained completely within the view, which is the XAML for the MainPage.xaml.

Code Snippet
  1. <phone:PhoneApplicationPage x:Class="WP8App.MainPage"
  2.                             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.                             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.                             xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
  5.                             xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
  6.                             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  7.                             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8.                             xmlns:viewModels="clr-namespace:ReusableLibrary;assembly=ReusableLibrary"
  9.                             mc:Ignorable="d"
  10.                             FontFamily="{StaticResource PhoneFontFamilyNormal}"
  11.                             FontSize="{StaticResource PhoneFontSizeNormal}"
  12.                             Foreground="{StaticResource PhoneForegroundBrush}"
  13.                             SupportedOrientations="Portrait"
  14.                             Orientation="Portrait"
  15.                             shell:SystemTray.IsVisible="True">
  16.  
  17.     <phone:PhoneApplicationPage.Resources>
  18.         <viewModels:CustomerViewModel x:Key="ViewModel" />
  19.     </phone:PhoneApplicationPage.Resources>
  20.     <!--LayoutRoot is the root grid where all page content is placed-->
  21.     <Grid x:Name="LayoutRoot"
  22.           Background="Transparent">
  23.         <Grid.RowDefinitions>
  24.             <RowDefinition Height="Auto" />
  25.             <RowDefinition Height="*" />
  26.         </Grid.RowDefinitions>
  27.  
  28.         <!--TitlePanel contains the name of the application and page title-->
  29.         <StackPanel x:Name="TitlePanel"
  30.                     Grid.Row="0"
  31.                     Margin="12,17,0,28">
  32.             <TextBlock Text="MY PHONE APPLICATION"
  33.                        Style="{StaticResource PhoneTextNormalStyle}"
  34.                        Margin="12,0" />
  35.             <TextBlock Text="Main Page"
  36.                        Margin="9,-7,0,0"
  37.                        Style="{StaticResource PhoneTextTitle1Style}" />
  38.         </StackPanel>
  39.  
  40.         <!--ContentPanel - place additional content here-->
  41.         <Grid x:Name="ContentPanel"
  42.               DataContext="{Binding Source={StaticResource ViewModel}}"
  43.               Grid.Row="1"
  44.               Margin="12,0,12,0">
  45.             <Grid.ColumnDefinitions>
  46.                 <ColumnDefinition></ColumnDefinition>
  47.                 <ColumnDefinition></ColumnDefinition>
  48.             </Grid.ColumnDefinitions>
  49.             <Grid.RowDefinitions>
  50.                 <RowDefinition Height="Auto"></RowDefinition>
  51.                 <RowDefinition Height="Auto"></RowDefinition>
  52.                 <RowDefinition Height="Auto"></RowDefinition>
  53.                 <RowDefinition Height="Auto"></RowDefinition>
  54.                 <RowDefinition Height="Auto"></RowDefinition>
  55.             </Grid.RowDefinitions>
  56.  
  57.             <TextBlock Name="textBlock2"
  58.                        Height="23"
  59.                        Margin="10,10,10,10"
  60.                        HorizontalAlignment="Right"
  61.                        Grid.Column="0"
  62.                        Grid.Row="0"
  63.                        Text="Select a Customer:"
  64.                        VerticalAlignment="Top"
  65.                        Width="164" />
  66.             <ListBox Name="CustomersComboBox"
  67.                      Margin="10,10,10,10"
  68.                      HorizontalAlignment="Left"
  69.                      Grid.Column="1"
  70.                      Grid.Row="0"
  71.                      VerticalAlignment="Top"
  72.                      DisplayMemberPath="FullName"
  73.                      SelectedItem="{Binding Path=CurrentCustomer, Mode=TwoWay}"
  74.                      ItemsSource="{Binding Path=Customers}" />
  75.             <TextBlock Name="textBlock4"
  76.                        HorizontalAlignment="Right"
  77.                        Grid.Column="0"
  78.                        Grid.Row="1"
  79.                        Text="Customer ID"
  80.                        Margin="10,10,10,10" />
  81.             <TextBlock Margin="10,10,10,10"
  82.                        HorizontalAlignment="Right"
  83.                        Grid.Column="0"
  84.                        Grid.Row="2"
  85.                        Name="textBlock5"
  86.                        Text="Name" />
  87.             <TextBlock Margin="10,10,10,10"
  88.                        HorizontalAlignment="Right"
  89.                        Grid.Column="0"
  90.                        Grid.Row="3"
  91.                        Name="textBlock9"
  92.                        Text="Phone" />
  93.             <TextBlock HorizontalAlignment="Left"
  94.                        Grid.Column="1"
  95.                        Grid.Row="1"
  96.                        Name="CustomerIDTextBlock"
  97.                        Text="{Binding ElementName=CustomersComboBox, Path=SelectedItem.CustomerID}"
  98.                        Margin="10,10,10,10" />
  99.             <TextBox HorizontalAlignment="Left"
  100.                      Grid.Column="1"
  101.                      Grid.Row="2"
  102.                      Width="219"
  103.                      Text="{Binding Path=CurrentCustomer.FullName, Mode=TwoWay}" />
  104.             <TextBox HorizontalAlignment="Left"
  105.                      Grid.Column="1"
  106.                      Grid.Row="3"
  107.                      Width="219"
  108.                      Text="{Binding Path=CurrentCustomer.Phone, Mode=TwoWay}" />
  109.             <Button Command="{Binding UpdateCustomerCommand}"
  110.                     Content="Update"
  111.                     Height="95"
  112.                     HorizontalAlignment="Right"
  113.                     Grid.Column="0"
  114.                     Grid.Row="4"
  115.                     Name="UpdateButton"
  116.                     VerticalAlignment="Top"
  117.                     Width="180"
  118.                     Grid.ColumnSpan="2"
  119.                     Margin="0,0,123,-72" />
  120.         </Grid>
  121.     </Grid>
  122. </phone:PhoneApplicationPage>

Again, it’s kind of hard to picture what this looks like just looking at the XAML, so we run the application to see that we’ve created a completely different view of the data yet still leverage the exact same PCL code.

image

OK, hopefully by now it’s starting to make sense.  We simply define different views per platform, providing optimal code reuse.

Defining a View for a Windows 8 Store App

Now that we’ve seen it’s completely possible to just define a view for each platform (so far, WPF and Windows Phone), let’s create one more just to show off.  This time, we’ll create a Windows 8 app.  Just like before, we reference the PCL.

image

We now inspect the MainPage.xaml and see that we can, again, create a view that is platform-specific while referencing the view model, model, and repository classes from the PCL.

Code Snippet
  1. <Page x:Class="WindowsStoreApp.MainPage"
  2.       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.       xmlns:local="using:WindowsStoreApp"
  5.       xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  6.       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  7.       xmlns:mylib="using:ReusableLibrary"
  8.       mc:Ignorable="d"
  9.       FontSize="30">
  10.     <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
  11.         <TextBlock x:Name="pageTitle"
  12.                    Text="My Store Application"
  13.                    Style="{StaticResource HeaderTextBlockStyle}"
  14.                    IsHitTestVisible="false"
  15.                    TextWrapping="NoWrap"
  16.                    VerticalAlignment="Bottom"
  17.                    Margin="0,0,30,40" />
  18.         <Grid>
  19.             <Grid.DataContext>
  20.                 <mylib:CustomerViewModel />
  21.             </Grid.DataContext>
  22.             <Grid.ColumnDefinitions>
  23.                 <ColumnDefinition></ColumnDefinition>
  24.                 <ColumnDefinition></ColumnDefinition>
  25.             </Grid.ColumnDefinitions>
  26.             <Grid.RowDefinitions>
  27.                 <RowDefinition Height="Auto"></RowDefinition>
  28.                 <RowDefinition Height="Auto"></RowDefinition>
  29.                 <RowDefinition Height="Auto"></RowDefinition>
  30.                 <RowDefinition Height="Auto"></RowDefinition>
  31.                 <RowDefinition Height="Auto"></RowDefinition>
  32.             </Grid.RowDefinitions>
  33.             <TextBlock Name="textBlock2"
  34.                        HorizontalAlignment="Right"
  35.                        Grid.Column="0"
  36.                        Grid.Row="0"
  37.                        Margin="10,10,10,10"
  38.                        Text="Select a Customer:" />
  39.             <ComboBox Name="CustomersComboBox"
  40.                        HorizontalAlignment="Left"
  41.                        Grid.Column="1"
  42.                        Grid.Row="0"
  43.                        VerticalAlignment="Top"
  44.                        Width="219"
  45.                        Margin="10,10,10,10"
  46.                        DisplayMemberPath="FullName"
  47.                        SelectedItem="{Binding Path=CurrentCustomer, Mode=TwoWay}"
  48.                        ItemsSource="{Binding Path=Customers}" />
  49.             <TextBlock Name="textBlock4"
  50.                        HorizontalAlignment="Right"
  51.                        Grid.Column="0"
  52.                        Grid.Row="1"
  53.                        Margin="10,10,10,10"
  54.                        Text="Customer ID" />
  55.             <TextBlock Name="textBlock5"
  56.                        HorizontalAlignment="Right"
  57.                        Grid.Column="0"
  58.                        Grid.Row="2"
  59.                        Margin="10,10,10,10"
  60.                        Text="Name" />
  61.             <TextBlock Name="textBlock9"
  62.                        HorizontalAlignment="Right"
  63.                        Grid.Column="0"
  64.                        Grid.Row="3"
  65.                        Margin="10,10,10,10"
  66.                        Text="Phone" />
  67.             <TextBlock Name="CustomerIDTextBlock"
  68.                        HorizontalAlignment="Left"
  69.                        Grid.Column="1"
  70.                        Grid.Row="1"
  71.                        Margin="10,10,10,10"
  72.                        Text="{Binding ElementName=CustomersComboBox, Path=SelectedItem.CustomerID}" />
  73.             <TextBox HorizontalAlignment="Left"
  74.                      Grid.Column="1"
  75.                      Grid.Row="2"
  76.                      Width="219"
  77.                      Margin="10,10,10,10"
  78.                      Text="{Binding Path=CurrentCustomer.FullName, Mode=TwoWay}" />
  79.             <TextBox HorizontalAlignment="Left"
  80.                      Grid.Column="1"
  81.                      Grid.Row="3"
  82.                      Width="219"
  83.                      Margin="10,10,10,10"
  84.                      Text="{Binding Path=CurrentCustomer.Phone, Mode=TwoWay}" />
  85.             <Button Name="UpdateButton"
  86.                      Command="{Binding UpdateCustomerCommand}"
  87.                      Content="Update"
  88.                      Height="95"
  89.                      Grid.Column="1"
  90.                      Grid.Row="4"
  91.                      VerticalAlignment="Top"
  92.                      Width="180"
  93.                      Grid.ColumnSpan="2"
  94.                      Margin="10,10,10,10" />
  95.         </Grid>
  96.     </StackPanel>
  97. </Page>

If we inspect the code-behind for this view, we’ll see that there is zero additional code needed.  Again, I present the code in all its bareness and glory.

image

Yet when we run the application, we provide a completely different view over the same exact view model, which then provides the interactions with the model.

image

By simply leveraging bindings to the view model, we can provide the platform-specific implementation (the view) that interacts with the platform-independent components in the PCL.

The next post in this series shows how to reuse PCL libraries to build an Android app using Xamarin.Android integration with Visual Studio 2013.  A future post will take a closer look at the newly announced Universal Apps and see how that plays a part in the whole cross-platform story. 

For More Information

Sharing Code between Windows Store and Windows Phone App (PCL + MVVM + OData)

Using Portable Class Library with Model-View-View Model

Build Android Apps With Xamarin Using Portable Class Libraries