mkale.com

Windows Phone Code Sharing

By December 16, 2011 9:44PM [link]

I've been working on making two apps (lite and pro) based off a shared codebase. On iOS, I do this with a single Xcode project with two targets. I include most of the same source files in both targets and can build each one separately. For the few differences between the apps, I use compiler flags to #define a different constant in each target and can use different code as needed.

I tried to do something similar on Windows Phone. I created two separate .csproj files for the Lite and Pro projects, but had trouble including the same files in both of them. I wanted to include many of the same .cs source files but keep the .xaml different, and the files in the "Properties" directory different. (i.e., AssemblyInfo.cs and friends.) I wasn't able to rename the "Properties" directory and have it work correctly, nor was I able to references .cs files that lived outside of the directory containing the .csproj file correctly. It's possible I was doing something wrong here and there is a better approach, but this is what I came up with.

Top level directory contains .cs files for business logic, model classes, etc. As much as possible. It also contains the directories for each project, and the bulk of the code behind logic in files called (e.g.) "MainPageXamlShared.cs". It looks like this:

directory winphone/
Statistics.cs  (business logic)
Contraction.cs  (model class)
MainPageXamlShared.cs  (shared code-behind)
ContractionTimer/MainPage.xaml
ContractionTimer/MainPage.xaml.cs
ContractionTimer/Properties/...
ContractionTimer/ContractionTimer.csproj
ContractionTimerLite/MainPage.xaml
ContractionTimerLite/MainPage.xaml.cs
ContractionTimerLite/Properties/...
ContractionTimerLite/ContractionTimerLite.csproj
... more files of course

I'm leaving out a bunch of files but this gives you an idea. The MainPage.xaml in each directory are the full xamls (with differences between the two apps), but the code behind is entirely shared. MainPage.xaml.cs in each directory looks like this:

using Microsoft.Phone.Controls;

namespace ContractionTimer {
    public partial class MainPage : PhoneApplicationPage {
    }
}

That's it! All the logic is in the MainPageXamlShared.cs in the parent directory, which I was able to reference from each project with no trouble:

using Microsoft.Phone.Controls;
using System;
using System.Lots.More.Of.These;

namespace ContractionTimer {
    public partial class MainPage : PhoneApplicationPage {
        private readonly TimeSpan TIME_INTERVAL_SECONDS = TimeSpan.FromSeconds(1);
        // ...
        public MainPage() {
            InitializeComponent();
            // ...
        }
        // well, you get the idea ...
    }
}

This allows me to at least share the bulk of the code between two different versions of the app. A couple of final notes:

History | Blog | mkale.com