Nick's .NET Travels

Continually looking for the yellow brick road so I can catch me a wizard....

Getting Started: Xamarin Forms with .NET Standard 2.0

In my earlier post Getting Started: Xamarin Forms with .NET Standard I covered how to create a new Xamarin Forms project which uses a .NET Standard 1.4 library to share the views between iOS, Android and UWP. At the time, whilst iOS and Android supported .NET Standard 2.0, support still wasn’t available for UWP. Almost immediately after publishing the blog post, Microsoft announced that Visual Studio 2017 preview 15.4 would allow UWP applications to reference .NET Standard 2.0 libraries. Unfortunately this didn’t work in the first drop, 15.4.0 Preview. This was just updated to 15.4.0 Preview 2 (Release Notes:, which brings with it the support we’ve been after. In this post, I’m going to repeat the previous post on getting started with .NET Standard, this time using .NET Standard 2.0 for the UI project.

Let’s walk through the basics – create a new Cross Platform App (same as before)


Select the Xamarin.Forms (UI Technology) and Portable Class Library (PCL) (Code Sharing Strategy) – Don’t pick the Shared Project option!


Select the Insider Preview version of UWP for both Minimum and Target version – this is required for .NET Standard 2.0 support. If you want to target earlier versions of Windows 10, you’ll have to stick with .NET Standard 1.4.


Next, we’re going to replace the PCL with a new .NET Standard library


I’ll copy the App.xaml, App.xaml.cs, MainPage.xaml and MainPage.xaml.cs from the PCL into the .NET Standard library, before deleting the PCL from the project (see for more detailed instructions).

The big difference is that I’m not going to change the default Target Framework, leaving it as .NET Standard 2.0.


Next I need to make sure I add and upgrade references to Xamarin.Forms to each of the projects – this isn’t actually required, since the stable release of Xamarin Forms will actually work with .NET Standard but I’ve been working with the pre-release version quite a bit lately, so I’ll go with that for this example.


I also need to remember to add a reference to the .NET Standard project to each of the head projects for iOS, Android and UWP.


If you attempt to build and run at this point iOS and Android should work without issue. UWP will most likely compile but will raise an exception “Could not load file or assembly ‘netstandard, Version=….” at runtime.


Essentially the UWP project structure has evolved a little, so you need to upgrade it. Now I think that you may be able to do this via package manager but I’ve never got it to work for UWP projects, so I will make the changes manually to the csproj file. Start by deleting the project.json file from the UWP project.

Next right-click the UWP project in Solution Explorer and select unload project. Next, right-click on the UWP project node and select Edit MySecondXamarinFormsApp.UWP.csproj.

Add a new PropertyGroup – this changes the way packages are referenced, eliminating the need for the project.json file, replacing it with references within the csproj file.



Next we need to add back the package references that were in the project.json – if you’re doing this on an existing project, you may want to keep the project.json file handy so you know which packages to add. In this case there are just two projects:

   <PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
   <PackageReference Include="Xamarin.Forms">


Now you can right-click on the UWP project in Solution Explorer and select Reload project. Trigger a rebuild and now you should be able to run the UWP project.


Getting Started: Xamarin Forms with .NET Standard

With the recent release of Visual Studio 2017 v15.3 (and subsequent patch release 15.3.1 and 15.3.2…. yes, it does say something about ship quality Sad smile) came the release and support for .NET Standard 2.0. The Xamarin team also made a lot of noise about support for .NET Standard 2.0; unfortunately this doesn’t yet translate into Visual Studio templates that easily get you started. My particular annoyance is the about of steps you need to go through in order to just spin up a new Xamarin Forms application that can reference .NET Standard libraries. I thought I’d piggyback of a post done a couple of months back by Pierce Boggan. Here goes:

Start by creating a new project in Visual Studio 2017, selecting the Cross Platform App (Xamarin) project template:


Next, select the template you want (I’m going with the Blank App), the UI Technology and Code Sharing Strategy. As I’m going to be walking through how to use Xamarin Forms, it makes sense to pick that as the option for UI Technology. Only select the Portable Class Library option. Don’t use the Shared Project – using a shared project will lead you down the evil road of using conditional compilation which will be a maintenance nightmare, just don’t use it. I don’t care how great you think it is, don’t use it. One last time, don’t use the Shared Project option.


Now that I’ve expressed my opinion on code sharing strategies, let’s click the OK button and get on with building our application. As the template goes through generating the head projects for iOS, Android and UWP, it will prompt you to select the target and minimum platforms for UWP. For the most part, unless you have specific target platform requirements for UWP, you can leave the default settings.


The generated solution will have four projects: three head or target platform projects (for iOS, Android and UWP) and a portable class library (PCL) which contains the XAML pages that will make up your Xamarin Forms application layout. In order to proceed with .NET Standard support we need to replace the PCL with a .NET Standard library. Whilst Visual Studio used to have a mechanism for upgrading a library from a PCL to a .NET Standard library, this has been removed. Now the easiest way is to simply create a new project, and copy the relevant files into the new project. From the Add New Project dialog, select the Class Library (.NET Standard) template.


I use the .UI naming convention for the library that will contain my XAML pages. Other developers use .Core but my preference is to separate my XAML pages away from my view models. Whilst technically with Xamarin Forms they can reside in the same library, I prefer to have a clean separation between them. I have <applicationname>.UI with my XAML pages in it and <applicationname>.Core with my view models, services, entities, essentially all the business logic for my application.

For this example I’m going to keep it simple and we’ll just create the .UI project for the moment.


I don’t need the default Class1.cs, so I’ll remove that. I’ll add a reference to the .NET Standard library to all the head projects.

I’m also going to drop the .NET Standard version back from 2.0 (now the default in Visual Studio) back to 1.4. Whilst the tooling has been updated for the head projects for iOS and Android to support .NET Standard 2.0, of course, UWP is still lagging the field, as so you won’t be able to use a .NET Standard 2.0 library until that’s fixed. To be honest though, not much is lost by lowering the version of the .UI project to 1.4 since all the features of Xamarin Forms are still there.


Next I’m going to copy App.xaml (and App.xaml.cs) and MainPage.xaml (and MainPage.xaml.cs) from the PCL into the newly created .NET Standard library. Once I’ve copied these files across I can remove the PCL project from the solution – this will remove the references to this library from each of the head projects. After coping these files across, you may well see a compilation error similar to the following:

1>------ Build started: Project: MyFirstXamarinFormsApp.UI, Configuration: Debug Any CPU ------
1>C:\Program Files\dotnet\sdk\2.0.0\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.DefaultItems.targets(274,5): error : Duplicate 'EmbeddedResource' items were included. The .NET SDK includes 'EmbeddedResource' items from your project directory by default. You can either remove these items from your project file, or set the 'EnableDefaultEmbeddedResourceItems' property to 'false' if you want to explicitly include them in your project file. For more information, see The duplicate items were: 'App.xaml'; 'MainPage.xaml'
1>Done building project "MyFirstXamarinFormsApp.UI.csproj" -- FAILED.

If you do, you just need to edit the project file for the .UI project and remove the App.Xaml and MainPage.xaml EmbeddedResource elements. The new project format includes files by default and the tooling isn’t smart enough to realise that the sample files are being added multiple times. Removing these elements will fix the compilation:

   <EmbeddedResource Include="App.xaml">
   <EmbeddedResource Include="MainPage.xaml">

The last thing to do is to make sure that the .NET Standard library references Xamarin Forms. I’m going to do that by right-clicking the solution node in Solution Explorer and selecting Manage Nuget Package for Solution.


I’m going to select the new prerelease version of Xamarin Forms (which is the one where they’ve apparently added .NET Standard support). In addition to adding a reference to Xamarin Forms to the UI project, I also take this opportunity to upgrade all the package references in the application. Note that I’ve even selected the Android support packages – this used to be a big No-No but with the latest version of the tooling you can now go ahead and update them, and I would definitely encourage you to do so.


Now, go make yourself a coffee – Nuget is slow, so slow! The good news is that once you’ve done all these steps, you’re ready to go with a .NET Standard based Xamarin Forms project. If you’re following this post to get started on your own project, you can finish up here, as you’re good to go.

Ok, so all of that, and what can we do. We’ll for a starters, it makes it super easy to add nuget packages such as BuildIt Forms which has a bunch of helper controls and features to get you building richer applications. Let’s add a reference to the BuildIt.Forms Nuget package the project:


After adding the reference to BuildIt.Forms we can make use the added controls. For example the ContentButton allows us to easily add a button that contains any XAML content, whilst still maintaining the pressed and hover states:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns=""
     <StackLayout VerticalOptions="Center"
         <Label Text="Welcome to Xamarin Forms!" />
             <Label Text="Press m!" />

I’ll cover more on the BuildIt.Forms library in coming posts.

Cryptic Build Failure in Release Mode for Universal Windows Platform Application

We’ve just managed to solve an issue that’s been plaguing us for a while when we attempt to do a Release build (either via the Store –> Create App Package, or just by setting the build configuration to Release) we were seeing an error message similar to:

RHBIND : error RHB0011: Internal error: 'declModule == m_pLoaderModule'

This error makes no sense, and there’s nothing at all helpful to go on from any of the usual logs etc. A quick search only returned two links, one of which was to a GitHub thread ( posted by Microsoft that talks about capturing a .NET Native Repro…. not quite what I was interested in. However, further down the post there’s a section entitled “Compilation Failure on Update 1” which lists almost exactly the error we were seeing. The section refers to a new feature called SharedLibrary but doesn’t really talk about how to turn it on or off. It does however link to another post

Initially I didn’t think that there was anything relevant in the post, since it was entitled “What’s new for .NET and UWP in Win10 Tools 1.1” and starts off talking about app-locally and shared appx framework packages. It then talks about how to enable this feature….but in the other post it said that SharedLibrary was on by default…. Anyhow, instead of following this post and setting the UseDotNetNativeSharedAssemblyFrameworkPackage to true (ie enabling it), I figured I’d try setting it to false (ie <UseDotNetNativeSharedAssemblyFrameworkPackage>true</UseDotNetNativeSharedAssemblyFrameworkPackage>). For example the Release section of the UWP project file now looks like:

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">

Doing this fixed the Release build for this application and allows us to create a package ready for Store deployment. Hope this helps others.

Microsoft Lumia 950, Windows Hello and Continuum

Due to an issue with the USB dock on my Lumia 640XL preventing me deploying apps for debugging, I went ahead and ordered a Lumia 950 XL which arrived today. The unboxing experience went well and as per most new phones there’s the normal down time whilst you transfer and reinstall apps on the new device. There were two features that I really wanted to try out:

Windows Hello

I’ve been using my Surface Book for a while now, so I’m used to the speed and convenience of the Windows Hello sign in experience which means I can just look at my monitor and it signs in. On the phone the experience is basically the same – it looks for you and signs you in. However, I do feel that it’s actually slower than simply tapping the pin code. At this stage I’ll leave Windows Hello enabled but I suspect that it may annoy me, more than it is a convenience.


I don’t have one of the continuum docks yet, and since I purchased a grey-imported phone I wasn’t eligible for, the Microsoft Australia offer for getting a free dock (personally I think this should be open to anyone willing to sync $700+ dollars into a Windows Phone at this point given the dire lack of feature complete apps). However, I do have a TV that has a Miracast dongle ( attached to it, so I went ahead and tapped the NFC pad, and 10 seconds later the device was connected, displaying out my TV. The phone turns into a track pad and the whole TV is used for whichever app is being displayed.

I went and downloaded an app we’ve just helped deliver - Looks brilliant running at full desktop size on a TV screen.

States v’s Regions for Multi-Window Applications

In previous posts I’ve talked a lot about visual states, application state and control states. However, one thing that I’ve been trying to wrap my head around is the disconnect that happens when you start to consider that an application can have multiple windows.What’s rather ironic is multi-window support was something we took for granted back when we were building complex line of business Windows Forms/WPF applications. However, the iOS era lead to the dumbing-down of application development – in the Apple world users are only able to do single operations and apparently can’t wrap their heads around anything more than a single screen full of data at a time. This lead to application models, and page/view lifecycles that assume that the application is either in the foreground, or in the background; no middle ground where the application is visible, just not in focus, which is the case in a multi-windowed environment.

The interesting side effect of a multi-windowed environment is less to do with having multiple applications open and visible at the same time but that a single application can have multiple windows open at the same time. One of the best features of the old Live Messenger application was that you could have each chat open in a separate window, each of which could be independently moved, pinned and closed. Currently, nearly every messaging application, be it Messenger (Facebook), WhatsApp, Skype or Line, use a similar single-window model that’s extremely painful when you are actively participating in multiple chats.

Of course, most platforms all support some limited form of multiple window support, for example when projecting the contents of the screen to an external monitor. The Universal Windows Platform has full support for the creation and management of multiple windows within a single application instance. A recent post on the Redmond Pie shows a concept of what multiple windows on an iPad would look like. It’s evident that multi-windowed applications are going to play an important part of all future platforms.

This leads me to my next challenge. In the context of a single window application we can think of the current page of the application as mapping to a state in the application. Transition from one state to another equates to moving between pages. Within the confines of a page, there may be multiple states; these map to visual states on the page. However, going the other direction, how do we represent multiple windows? Windows don’t map to another higher level set of states, since there may be any number of windows opened, and they can all exist in relative independence.

So, we need a different concept to represent them, which I’ve termed Application Regions. By default all applications have a default or start up region. A region has a current states, which will normally correspond to the current page or view. Regions can be created and closed independently, and usually correspond to separate windows (although I’m currently considering whether a region can manifest itself in other ways). Regions can also have different startup pages (ie a different startup state), and might in fact have a completely different set of states.

In the same way that we need a state manager to assist with the management and tracking of states, we’ll need a region manager that understands how to create, track and close regions. Whilst the region manager will itself live in the platform agnostic core of our application, it will of course need a mechanism to spawn new windows (ie when a region is created). The region manager will also need to be clever enough to do the right thing when run on a platform that doesn’t support multiple windows. On such an environment, when a new region is spawned, the new set of pages/view will simply have to be added to the navigation stack of the existing window; when the user closes the region, the pages/views will be popped off the stack, returning to the last page/view of the previous region.

This is just some early stage thoughts on the concept of application regions v’s application states.

Cross Platform Visual States

Last year I posted on “Taking Visual States Cross Platform to iOS and Android with Xamarin” and is a topic that I often come back when discussing the design and development of mobile applications. Let’s start by discussing what visual states are and why they’re important when building applications (and this really applies to any application, not just mobile applications). During the design of an application it’s common to prepare wireframes and visual designs that document each page, the key elements on each page and any associated behaviour. This typically includes documenting when elements are hidden or shown, often in response to either data changes or user interactions. The following screenshots show a recent application we worked on for Hungry Jack’s for Windows 10. This is the same page of the same application, running on the same device, just with a different window size. As you can see the difference between the first two images is quite significant as the navigation bar switches from being at the bottom (similar to what you’d expect for mobile) to on the left side. The third image simply augments the position of elements further to make better use of the available screen size.

image image image

Thorough analysis during the design phase will reveal all possible layout combinations for a page; these combinations are what we refer to (at least in the Windows/XAML world) as visual states. In the case of the screenshots from the Hungry Jack’s application, each of these layouts represents a different visual state for this page. If you don’t take the time to determine what visual states exist on each page and what triggers a transition between visual states, during development you’ll find yourself toggling attributes on element on the page in an attempt to recreate each required combination. This lack of a structured approach makes it not only hard to layout each page, it also makes it hard to test as there is no definitive list of layouts that need to be verified.

On the Windows platform, Visual States are something we take for granted; they can be declared in XAML and Blend has support for designing each visual state. However, other platforms are not so blessed and have to resort to changing attributes manually in code. Some cross platform technologies make use of data binding to allow visual elements to be dynamically updated based on changes in the corresponding data (ie the view model). These include MvvmCross and Xamarin.Forms. However, data binding should be reserved for updating data values on a view, not controlling the visual states on a page.

Learning to develop for the Windows platforms, developers go through a series of learning steps.

  • Coding Changes: Most developers come from building applications or web sites where they’re used to having to set data values in code.
  • Data Binding: The first step along the progression is learning how to use data binding to update content on the page (eg Text on a Textblock)
  • MVVM: After seeing the benefit of data binding, the next step is to appreciate the separation of concerns that MVVM offers. At this point developers often look at what MVVM libraries there are out there and usually settle on something like MvvmCross, MvvmLight, Caliburn.Micro, Prism etc
  • Converters: Equipped with the new found power of data binding, developers often go nuts and start data binding everything, including using properties on the view model to control when items should be visible. This is where they look to use converters to adapt properties on the view model (eg XYZIsVisible which would be a bool) to attributes on visual elements (eg XYZ.Visibility which is a Visibility). The issue with this is that at design time, in a tool like Blend, it’s very difficult to see what the layout looks like. You can’t simply change the Visibility property on elements, since they’re now data bind. You can temporarily remove the data binding, but then of course you forget to put it back and then spend hours trying to work out why the application is broken.
  • Visual States: Enter Visual States…. instead of data binding attributes that control the layout of a page, it’s better to use visual states to define what elements are visible and any layout changes required for a particular layout. Blend supports design time editing of visual states and the ability to visualize any combination of visual states from different state groups
  • View Model States: Eventually developers realise that not only should they use visual states, they should track and control them from their view model, thus making yet another aspect of their application testable. I’ve talked about this a couple of times (,,

Ok, so now that you have the basics on what a visual state is, and some background on why I believe visual states are so important, let’s discuss the elephant in the room….. Visual States only exist in XAML on the Windows platform…. making it very difficult to use visual states when building cross platform applications. So, what can we use when building cross platform? Well let’s go through the progression that developers go through. As you’d expect, all platforms support developers being able to adjust values via code. Unfortunately, this is where most developer technologies end, for example neither iOS (Objective-C, Swift) or Android (Java) support data binding out of the box. There are some third party solutions that attempt to bridge this gap, such as the data binding support in MvvmCross and Xamarin.Forms. In fact both these options provide not only the ability to data bind, but also enable MVVM and support using converters as part of data binding.

In actual fact there’s no requirement to have data binding (and subsequently MVVM and the use of converters) in order to start using visual states to control layout. However, again there’s almost no platform, or even third party, support for defining visual states.Over the weekend, I was experimenting with Xamarin.Forms and was thinking about how to define and transition between visual states. Whilst it would be nice to do it declaratively in XAML, I thought I’d better walk before I run, so I figured I’d work out a way to define visual states in code. Before getting started I thought though the basic mechanics of how visual states should work:

- Visual States should be declared in groups, and each group can only have one active visual state at any given time

- A visual state should define any number of value actions

- A “value action” defines setting a property on an element to a specific value

- The visual state manager should be able to change to a specific visual state

- Changing to a specific visual state, should only adjust the current state of the group that the visual state belongs

I’ve always felt that one of the weaknesses of Visual states on the XAML platform is that they’re named using a string, and the only way to reference them when changing state, is using a string literal. So, for my attempt at a visual state manager I’m going to have my visual states defined as an enumeration. In fact, each group of states will use a different enumeration type – thus each visual state corresponds to a unique enumeration value. The end game is to be able to declare visual states in a relatively fluid manner, as shown in the following example which defines two groups based on the enumerations SecondStates and SecondStates2.

                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .Change(x => x.FontSize, (x, c) => x.FontSize= c)
                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .Change(x => x.FontSize, (x, c) => x.FontSize = c)
                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .Change(x => x.FontSize, (x, c) => x.FontSize = c)
                .Change(x => x.TextColor, (x, c) => x.TextColor = c)
                .Change(x => x.FontSize, (x, c) => x.FontSize = c)

In my next post we’ll look at the different classes that make up the visual state manager and the extension methods that allow for the fluid declaration seen in this example.

SplitView Bug in the Universal Windows Platform (UWP)

Last week we were trying to resolve an issue that had been raised in an application we were building for the Universal Windows Platform, where the user had to press the back button twice in order to navigate back to the previous page. Initially we thought that we must be subscribing to the hardware back button on Windows 10 Mobile, as the issue seem to only manifest itself on mobile. However, after eliminating all calls to subscribe to the back button, we were still seeing the same issue. After a bit of further testing the issue only seemed to arise if we were navigating to a new page with the pane of the SplitView visible, but not always…. Eventually we tracked it down to the scenario where the DisplayMode is set to Overlay and the pane of the SplitView is visible (ie IsPaneOpen set to true). Navigating to a new page without first either changing the DisplayMode to Inline, or closing the pane, will result in the pane staying open, and unfortunately it still keeps the event handler on the BackRequested event on the SystemNavigationManger.

SplitViewFail sample

Simple solution: make sure that you force the pane closed before navigating by setting IsPaneOpen to false (assuming the DisplayMode is set to Overlay).

Ignite Session Recordings

Earlier this month I delivered two sessions at Ignite Australia. The recording for these sessions are now available for watching

Application Development for the Universal Windows Platform
This session provides an overview of the Universal Windows Platform (UWP), a single platform that developers can target to build applications that will run across a myriad of devices. After years of progressive convergence, UWP offers a single application model, a single developer experience and a single store. The session will discuss building applications that can run on any device, whilst still being able to leverage the individual device features. It'll provide a roadmap for tools, frameworks, and guidance on building for the Universal Windows Platform.

Bare Metal Development with the Universal Windows Platform
Ignite Australia
The Universal Windows Platform offers developers a unique opportunity to build applications that run on an extensive range of devices. However, this comes the challenge of how to scale the user experience and how to adapt to different device capabilities. This session will dig deep into the use of Visual States, adaptive triggers, device family and feature detection, new binding syntax and new controls.

Changing DataContext and Compiled Data Binding in Universal Windows Platform Applications

Back in April I talked briefly about Compiled Data Binding and how it improves performance throughout your XAML application by eliminating all the reflection calls that go on in the background with traditional data binding. Recently I've been spending more time investigating the best way to structure code and design time data to ensure high quality applications. One of the easy pitfalls with the x:Bind syntax is a lack of understanding of the context of the data binding.

To start with, let's recap how traditional data binding works: Elements on the page have a DataContext, which you can think of as the object that is being data bound to. The DataBinding expression includes a Path, which determines the property on the DataContext that a particular attribute on an element is being data bound to. By default the DataContext flows down the page/usercontrol as each element inherits the DataContext from its parents. However, it is possible to override the DataContext by setting it explicitly for each element. There are plenty of sites/pages that can provide more detail on this form of data binding.

The new compiled data binding, which I'll refer to as x:Bind, tries to eliminate any use of reflection at runtime. In order to do this, the compiler generates a large quantity of code to connect the data entities and the visual elements. This means that the compiler must know Type information about both the attribute on the visual element, and the properties on the element being data bound. The starting point is that the context for x:Bind expressions on a Page is the Page itself, and similarly for a UserControl, it is the UserControl itself. If we assume that the data we want to data bind to is within our ViewModel, then we need to expose the ViewModel as a property on the Page. For example:
public MainViewModel CurrentViewModel => DataContext as MainViewModel;
and then in the XAML for the Page it can be referenced as follows:
<TextBlock Text="{x:Bind CurrentViewModel.Name, Mode=OneWay}" />
This references the Name property on the MainViewModel entity returned by the CurrentViewModel property on the page. What's not immediately obvious here is that despite indicating that the Mode is OneWay (ie it should detect changes) there is no code that notifies the data binding framework if the CurrentViewModel changes. This could happen if the DataContext changes, for example in the following code where the OnNavigatedTo method has a small latency before it sets the DataContext.
protected async override void OnNavigatedTo(NavigationEventArgs e)
    await Task.Delay(2000);

    DataContext = new MainViewModel();
In this case, the underlying DataContext is updated after 2 seconds to the new instance of the MainViewModel. This means that the CurrentViewModel value has also changed. However, there has been no attempt to notify the data binding framework, and subsequently the page, of this change. There are a number of ways to address this issue, the two I'm going to present here both rely on the Page implementing the INotifyPropertyChanged interface, exposing an event PropertyChanged, which the data binding framework will listen for.

Option 1 - Raise the PropertyChanged event manually after setting the new DataContext eg
DataContext = new MainViewModel();
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CurrentViewModel"));
Option 2 - Intercept the DataContextChanged event and then raise the PropertyChanged
public MainPage()

    DataContextChanged += MainDataContextChanged;
private void MainDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CurrentViewModel"));
Both of these options use a hardcoded property name, CurrentViewModel, which is not recommended. A last option, that might appear more complex to begin with, has the advantage of being simple, clean and less riddled with string constants. It starts with a Wrapper class, which provides a level of indirection between the Page and the ViewModel:
public class Wrapper<T>:INotifyPropertyChanged
    public T Entity { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;

    public Wrapper(FrameworkElement element)
        element.DataContextChanged += Element_DataContextChanged;

    private void Element_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
        if (args.NewValue is T)
            Entity = (T) args.NewValue;
            Entity = default(T);
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Entity"));

    public virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
And using this entity is simple as you just need to define the type of ViewModel:
public Wrapper<MainViewModel> Data => new Wrapper<MainViewModel>(this);
The only other difference is that there is an extra level of indirection in the x:Bind expression.
<TextBlock Text="{x:Bind Data.Entity.Name, Mode=OneWay}" />

Now as the DataContext on the Page changes the Wrapper class will detect the change and raise the PropertyChanged event indicating that the "Entity" has changed. Since x:Bind connects to any object in the binding path that implements INotifyPropertyChanged, it will handle this event and look for the updated Entity property, which will be the new DataContext value.

As you start to work with x:Bind, you will notice that your binding expressions are longer than you'd be used to. Don't worry about this, since the data binding itself will be orders of magnitude quicker

Application Development Using States and Transitions

Having worked with each of the different XAML based technologies Microsoft has released (WPF, SL, WP, Win, UWP...), I've long been a proponent of the use of visual states. Jerry Nixon discusses using visual states to build Windows 8.1 application. I've written articles that talk about using visual states for changing page layout to reflect states within a view model. Let me talk briefly about why I favour visual states and why the visibility property is often misused.... then we'll get onto discussing using states for building applications.

Developers new to working with XAML discover that they can hide/show items on the page by data binding a Boolean property on the view model (this assumes they're using mvvm/data binding) with the visibility property on an element. This of course requires a Boolean to visibility converter. It works nicely and assuming the developer has implemented INotifyPropertyChanged and is raising the PropertyChanged event correctly, the elements on the page will hide/show as required.

Whilst there isn't anything wrong with this approach, it makes it difficult to design the layout in Blend. In order to hide/show elements, you have to modify the design time data (assuming you've bothered to create design time data). The alternative is to use visual states to describe how the page looks for each state. Blend for Visual Studio includes a States window which allows for one or more states to be invoked, making it easy to create, view and edit visual states, at design time!

Ok, time to move on an talk more about using states as a foundation for application development. Unfortunately we can't jump there yet as we need to first look at different levels of how an application hangs together. Rather than get into a discussion on the similarities and differences between application platforms, let's just look at the Windows platform (this should apply to Windows Phone, Windows 8.x and Windows 10):

- An application typically has a frame, within which it navigates between pages

- A page can be made up of any number of visual state groups, and can have a single visual state selected at any time from each visual state group. Animations can be run as part of transitioning between states.

- Controls (including Usercontrols) can contain their own visual states that determine how they look under various conditions (pressed, checked, selected etc).

What's interesting about this is that the navigation between pages is actually the odd one out. Most application developers devote a large portion of the application development process to ensuring the navigation between pages is correct. They spend very little time working through the visual states of pages (often hacking away at hiding/showing elements on the screen). So, what happens if we make the assumption that each one of these scenarios can be expressed as a series of states?

As a starting point, we'd need a definition of a state. In the past, to keep the states of a view model separated from the visual states on a page I typically create an enumeration which has values that have the same names as the visual states. The view model then keeps track of which state is currently selected. Changing the current state raised a StateChanged event, which is handled by the page where it invokes the GoToState method on the VisualStateManager. My basic definition of a state will be an extension of this where the IStateDefinition is based on an enumeration type (well, at least a struct):

public interface IStateDefinition<TState> where TState : struct
    TState State { get; }

with a simple implementation:

public class BaseStateDefinition<TState> : IStateDefinition<TState>
    where TState : struct
    public TState State { get; set; }

And we can then define an interface for an entity which maintains current state, allows for a change in state and raise an event when the state changes:

public interface IStateManager<TState> : INotifyPropertyChanged
    where TState : struct
    event EventHandler<StateEventArgs<TState>> StateChanged;

    TState CurrentState { get; }

    IDictionary<TState, IStateDefinition<TState>> States { get; }

    Task<bool> ChangeTo(TState newState, bool useTransition = true);

The first instinct would be for the view model to implement this interface, but this won't work since the view model would have to implement the interface for each state group that it needs to track. This means we need an implementation of this interface that tracks current state for each state group:

public class BaseStateManager<TState> :
    NotifyBase, IStateManager<TState>
    where TState : struct
    public event EventHandler<StateEventArgs<TState>> StateChanged;

    public TState CurrentState { get; private set; }

    public IDictionary<TState, IStateDefinition<TState>> States { get; set; }

    public async Task<bool> ChangeTo(TState newState, bool useTransitions = true)
        var current = CurrentState;
        if (current.Equals(newState)) return true;

        CurrentState = newState;

            StateChanged?.Invoke(this, new StateEventArgs<TState>(newState, useTransitions));
        catch (Exception ex)
            // Ignore any errors caused by the event being raised, as
            // the state change has still occurred
        return true;

We'll use this as the basis from which we can track states at an application, page and control level.

Microsoft and The Smith Family via the #WeSpeakCode Program Delivers Coding to Students at Mitchell High School on Windows 10 as part of #UpgradeYourWold Campaign

Yesterday I had the privilege of being involved in the delivery of introductory computer science and programming material to year 10 and 11 students out at Mitchell High School in Blacktown. The material was from which has a fantastic repository of material for high school students (specifically which is the course we were delivering).

This program was a combined initiative from The Smith Family and Microsoft and the first day (yesterday) aligned with the release of Windows 10. It was fantastic to see the energy in the room and the excitement from the students as they played and explored all the new features of Windows 10.

It was also great to see the media pick up what a great experience this was:

Launching Windows Store Applications from Code in Windows 10

On Windows 8/8.1 after installing an application from the Windows Store it was possible to interrogate the registry and find the AppUserModelId which could then be used to launch the application. This process is described in more detail here -

There are a couple of ways to launch the application using the AppUserModelId:

- The first (as the link suggests) is to use the launcher utility that comes with the SDK eg:
C:\Program Files (x86)\Windows Kits\8.0\App Certification Kit\Microsoft.Windows.SoftwareLogo.AppxLauncher.exe “AppUserModelId

- The other way is to use the ApplicationActivationManager ( which can be used as follows:

uint pid;
var mgr = new ApplicationActivationManager();
mgr.ActivateApplication("[AppUserModelId]", null, ActivateOptions.None, out pid);

This technique relies on getting the AppUserModelId from the following Registry:


The installation process for Store applications on Windows 10 doesn't create this Registry key, which means we need another way to determine the AppUserModelId. I haven't found a definitive way to do this but I did manage to find a way which seems to work. Essentially you need to append "!App" to the package family name of your application (not the package full name).

If you haven't played around with the powershell commands for installing and querying installed packages, it's worth taking a look. For example to get a list of all packages for a particular publisher you can issue the following powershell command:

get-appxpackage -publisher "OID.0.9.2342.19200300.100.1.1=6434210, CN=Built to Roam Pty Ltd, OU=Built to Roam Pty Ltd"

This will return a listing for each application such as the following:

Which, as you can see contains the PackageFamilyName - add "!App" and you have a string that should work as the AppUserModelId, allowing you to launch the application from code.

Visual Studio 2015 RTM and the case of the missing Microsoft Advertising SDK for Windows 8.1

I just got around to upgrading to VS2015 RTM having run the RC since it was available (just as an aside VS2015 has been the only version of Visual Studio that I've been running for quite some time now). And as Murphy's law goes, the first project I open doesn't build and run - OMG what pain do I now need to endure?

It appears that someone has made the decision to remove the Windows 8.1 Advertising SDK (perhaps due to the recent sale of MS advertising assets), which means my Windows 8.1 application is now missing a reference.  According to the Ads in Apps website ( the SDK is installed in VS2013 update 2 or later (clearly not the case)

Luckily, a bit of searching revealed the SDK available via Visual Studio Gallery at

Compiled DataBinding in Windows Universal Applications (UAP)

This question on stackoverflow which references the Windows 10 jumpstart videos ( raises the topic of compiled data bindings. Currently there is no documentation about this feature and I doubt that we’ll see much out of Microsoft prior to Build. However, the x:Bind syntax is available in the insiders preview of the Windows 10 SDK so I figured I’d explore it a little.

Let’s start with a simple expression:

<TextBlock Text="{x:Bind}" />

When you add this to a page and run it, you’ll see the Type name of the page displayed in the TextBlock (eg CompiledDataBindingSample.MainPage). In order to examine this further let’s create a simple custom control with a dependency property and corresponding change handler:

public class CustomControl : Control
    Windows.UI.Xaml.Markup.IComponentConnector x;

    public string Test
        get { return (string)GetValue(TestProperty); }
        set { SetValue(TestProperty, value); }

    // Using a DependencyProperty as the backing store for Test.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty TestProperty =
        DependencyProperty.Register("Test", typeof(string), typeof(CustomControl), new PropertyMetadata(null, TestChanged));

    private static void TestChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        var newData = (d as CustomControl).Test;

Now let’s add an instance of this control onto the page and data bind to the Test property:

<local:CustomControl Test="{x:Bind}" />

When this is run we can set a breakpoint on the Debug.WriteLine and we can examine the newData object. What’s interesting is that the newData object is the instance of the page that is hosting the control. In other words, the value being passed into the binding expression is the page itself (in this case an instance of MainPage) – this explains why in the TextBlock showed the type name, as this is the default ToString() value. This is interesting in itself as it means that the context for data binding with x:Bind is the page itself, in contrast to the default DataContext of null when using Binding.

The other thing that’s worth looking at is the Call Stack window. The first two frames make sense, being the set and change handler for the dependency property but then it gets interesting as it references a class called MainPage_obj1_Bindings with methods such as SetValue_obj3_Test, Update_, InitializeCore, Initialize etc.


At this point I think it’s time to go take a look at what’s been generated when the application was compiled. In this case we’ll use ILSpy to get a list of the classes that make up the application. As you can see from this screenshot MainPage has a couple of nested types, MainPage.IMainPage_Bindings and MainPAge.MainPage_obj1_Bindings, along with a field/property combination that exposes an instance of MainPage.IMainPage_Bindings. There is also an additional method, Connect, which has been injected into the MainPage during compilation.


A further examination of the base types collection shows that in addition to inheriting from Page, MainPage implements Windows.UI.Xaml.Markup.IComponentConnector, which no surprises defines a method, Connect(int, object). So, what does this method do? Using ILSpy to inspect the contents on the Connect method we can see that it generates an instance of the MainPage_obj1_Bindings class and associates it with the elements on the page (in this case the TextBlock and the CustomControl). Clearly this method is going to be invoked during the initialization phase of a page.

Now, let’s turn our attention to the MainPage_obj1_Bindings class. It would appear that this class has instance variables for each of the elements that has an x:Bind expression. In this case it has variables obj2 (TextBlock) and obj3 (CustomControl). It also has some generated methods such as SetValue_obj2_Text which explicitly sets the Text value on the TextBlock. This makes me think back to a time before data binding where properties had to be explicitly set in code. Whilst data binding has been an effective way for developers to declaratively wire up properties to underlying data, it did add a significant overhead and subsequent performance hit – for large data sets this can be quite significant and hard to work around. By the looks of these generated methods, it would appear that by converting the data binding expression into compiled code, some of the performance overhead of data binding can be overcome.

Ok, so now that we’ve taken a bit of a look at some of the aspects of compiled data binding, let’s go back to XAML and take a look at extending the binding expression to include a path. In most cases we’ll want to bind attributes on the visual elements to properties on a view model. The question is how to do this using x:Bind. Let’s see what happens when we add ViewModel to the binding expression:

<TextBlock Text="{x:Bind ViewModel}" />

Normally, if you add a path to a binding expression that isn’t valid it will compile and run without any issues. In this case, there is no ViewModel property on the MainPage, so when the application is compiled the following build error is generated:

Invalid binding expression 'MyProperty' : Unrecognized property 'MyProperty' at offset '0'

Let’s add a ViewModel property to the MainPage:

public MainViewModel ViewModel { get; set; }

public MainPage()
    ViewModel = new MainViewModel();


The MainViewModel class exposes a property, HelloText, and implements the INotifyPropertyChanged interface. Of course, normally this would be implemented in a base class with an OnPropertyChanged or RaisePropertyChanged helper method.

public class MainViewModel : INotifyPropertyChanged
    private string hello = “Hello World”;
    public string HelloText
        get { return hello; }
            hello = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("HelloText"));
    public event PropertyChangedEventHandler PropertyChanged;

In order to reference the HelloText property, we’ll extend the binding expression:

<TextBlock Text="{x:Bind ViewModel.HelloText}" />

Running this appears to work with the text “Hello World” appearing in the TextBlock. Let’s try updating the HelloText. A simple Run method will update the HelloText property every second.

public async void Run()
    var i = 0;
    while (true)
        await Task.Delay(1000);
        HelloText = "Hello " + i++;

Unfortunately this doesn’t seem to do anything, with the TextBlock not updating. This behaviour is consistent of a OneTime data binding. Let’s add Mode=OneWay to the binding expression.

<TextBlock Text="{x:Bind ViewModel.HelloText, Mode=OneWay}" />

Now the TextBlock updates every second as we’d expect. So it appears that unlike a traditional Binding, the x:Bind expression defaults to a OneTime mode, instead of OneWay. ILSpy also indicates that the MainPage_obj_Bindings has a sub-class, MainPage_obj1_Listener, which is designed to hook up to the INotifyPropertyChanged.PropertyChanged event. This again will help ensure updates are passed to the appropriate elements without any need for Reflection based calls.

Build it Beta for Windows and Windows Phone

Over the last couple of weeks we’ve done some major work to Build it Beta which will significantly improve and simplify the process of getting Build it Beta installed and setup across Windows and Windows Phone. If this is the first time you’ve heard of Build it Beta, it is a home-grown solution for the deployment of Windows platform applications. The primary scenario that Build it Beta solves, is the need for developers to deploy applications to testers so that they can provide feedback. It does this by leveraging the enterprise deployment capabilities of the Windows platform, where applications can be signed using a enterprise signing certificate and then deployed to devices that trust that certificate.

Supported platforms

The following Windows platforms are supported by Build it Beta for the installation of test applications.

Windows Phone 8.0
Windows Phone 8.1
Windows 8.1
Windows 10 (Phone and desktop)

Supported application platforms

Applications targeting the following platforms are supported by Build it Beta

Windows Phone 7.x (XAP)*
Windows Phone 8.0 (XAP)
Windows Phone 8.1 (XAP)
Windows Phone 8.1 (APPX)
Windows 8.0 (APPX)*
Windows 8.1 (APPX)
Windows 10 UAP (APPX)

*Build it Beta supports signing and deploying applications targeting Windows Phone 7.x and Windows 8.0. However, due to lack of enterprise distribution support in Windows Phone 7.x there is no way to deploy applications to those devices. Windows Phone 7.x applications can only be tested on Windows Phone 8+ devices. The Windows version of Build it Beta targets Windows 8.1 so there is no support for deploying to Windows 8.0 devices. Windows 8.0 applications need to be tested on Windows 8.1+.

Here are some useful links for getting started with Build it Beta

Distribution of Application for the Windows Platform for Testing

Last year I wrote an article for Visual Studio Magazine entitled Enterprise Distribution of Windows Phone Applications which looks at the requirements and steps required to deploy Windows Phone applications. The process for distributing Windows desktop/slate applications is slightly different but essentially involves signing the appx with an appropriate code signing certificate that is trusted by those computers that the application will be distributed to. We’re using these same techniques with Build it Beta to help developers distribute their applications for testing. Recently we’ve done a number of bug fixes and improvements and now have support for Windows Phone 8.0,  Windows Phone 8.1 (Silverlight), Windows Phone 8.1 (Appx), Windows 8.0 and 8.1, and now Windows 10 applications. There is still a bit of work to go in rounding off some of the rough edges but we’re really keen for developers to start using it.

We’ve also just created a new Build it Beta blog where we will be posting a series of post talking about distribution of applications for testing both in the generic sense (covering signing and enterprise distribution) and of course how Build it Beta works. Don’t forget you can follow Build it Beta on Twitter as well.

Windows 10 Jumpstart Training

Whenever I try to locate the jumpstart training for the Windows 10 Developer Preview tools it always seems to take longer than expected. Anyhow, I thought I’d re-post the direct links to each of the sessions here so that at least I can find them easily next time:

Developer's Guide to Windows 10 Preview- (01) Getting Started

Developer's Guide to Windows 10 Preview- (02) Start Simple- Hello World

Developer's Guide to Windows 10 Preview- (03) Migrating 8.1 Apps to Windows 10

Developer's Guide to Windows 10 Preview- (04) Extension SDKs

Developer's Guide to Windows 10 Preview- (05) SplitView Control

Developer's Guide to Windows 10 Preview- (06) Maps

Developer's Guide to Windows 10 Preview- (07) Pen & Ink

Developer's Guide to Windows 10 Preview- (08) RelativePanel Control

Developer's Guide to Windows 10 Preview- (09) Adaptive Triggers

Developer's Guide to Windows 10 Preview- (10) App-to-App Communication

Developer's Guide to Windows 10 Preview- (11) New XAML Controls and XAML Transform 3D

Developer's Guide to Windows 10 Preview- (12) App Services

Developer's Guide to Windows 10 Preview- (13) Action Center

Developer's Guide to Windows 10 Preview- (14) Evolving the Web Platform

Unable to Activate Windows Store App

I was running up one of our Windows 10 projects today and I encountered a somewhat cryptic error stating that Visual Studio was “Unable to activate Windows Store app…. The … process started, but the activation request failed with the error ‘The app didn’t start’”.


I figured there would be more information in the event log but this was not the case, with only this same message appearing there. Luckily it turns out that this issue isn’t specific to Windows 10 applications, and it was in fact this post that clued me on to removing the somewhat unnecessary app.config file that was still in my solution structure. Removing this file worked an absolute treat, although I can’t seem to work out why it fails since Visual Studio does sometimes warn about multiple versions of an assembly being referenced.

Package Manifest for Windows 10

As the tools for Windows 10 applications are still in preview there are some limitations and some features that aren’t quite ready yet. One of these is the designer for the package.manifest file, so the question is how do you know what elements can go in the manifest file. The manifest file is validated using a number of .xsd files that exist in the folder C:\Program Files (x86)\Windows Kits\8.2\Include\10.0.10030.0\winrt


These include the various namespaces defined at the beginning of the package.manifest file: