In my day to day work, I work on building not one, not two, but three .NET API's. One for Silverlight, one for WPF, and one for Windows Phone. However, since this is all based on the same technology (.NET and XAML), we reuse most of our code for all 3 (a rough estimate is 99% is the same code files). That's pretty cool, because I can create one feature in for instance Silverlight, and WPF and Windows Phone will instantly have it.
...well except if I hit one of those inconsistencies that makes up the remaining 1% of code differences. I've searched through our code and looked for the most common code differences in the API's, and the following series will cover these.
When you do need to write platform specific code, you can use a compiler conditional to do it. By default a Silverlight project will have a "SILVERLIGHT" conditional declared that you can use to exclude or include code for a specific platform. This is done by surrounding the code with a #if [condition] ... #endif section. Example:
//Silverlight and Windows Phone
If you are writing code for Windows Phone as well, note that this is also a Silverlight app, and will compile with the SILVERLIGHT conditional. However, Windows Phone also has a default conditional you can use to exclude/include features separate from Windows Phone:
#if !SILVERLIGHT || WINDOWS_PHONE
//Windows Phone and WPF
#if SILVERLIGHT && !WINDOWS_PHONE
//Silverlight but NOT Windows Phone
You will see these conditionals used in the upcoming blogposts to separate the code differences between the platforms. Click to select a topic below:
- WPF vs. Silverlight - Part 1 - Custom Controls Theme
- WPF vs. Silverlight - Part 2 – XamlReader
- WPF vs. Silverlight - Part 3 - Creating Bitmaps Programmatically
- WPF vs. Silverlight - Part 4 – Animations
- WPF vs. Silverlight - Part 5 - XAML Control Instantiation
- WPF vs. Silverlight - Part 6 - Debug.WriteLine
- WPF vs. Silverlight - Part 7 - Case sensitivity
- WPF vs. Silverlight - Part 8 - Reusing code in Visual Studio #1
- WPF vs. Silverlight - Part 9 - Reusing code in Visual Studio #2
- WPF vs. Silverlight - Part 10 - XAML Parser Differences
- WPF vs. Silverlight - Part 11 - Silverlight on Phone vs. Browser
- More to come… keep checking back…
A note on our development approach: We generally build a new feature for Silverlight first. Since Silverlight is a subset of WPF, we are less likely to be using an API that's not available in WPF (since it has most of what Silverlight has). We then test the code in WPF and tweak if necessary (tweaks rarely needed). Windows Phone is Silverlight (albeit roughly an earlier version), so we might exclude a feature here and there, but generally the only differences here are various simplifications for performance reasons (most of which isn’t needed with the upcoming Mango release), and of course sometimes retemplating for a smaller touch-centric screen.