25 Sep 2012

For more posts in this series, see the series index.

With one of my earliest apps I kept having a problem with a COM exception being raised, when trying to setup the Share & Settings event handlers. A key factor is it didn’t happen all the time. I had it the following code on the constructor of my ViewModel class:


this.DTM = Windows.ApplicationModel.DataTransfer.DataTransferManager.GetForCurrentView();
DTM.DataRequested += ShareRequest;

Eventually I figured out that the exception was raised if the event was already attached, but this was in my view model class and this was in the constructor of the class (so should be new and fresh every time) – this didn’t make much sense to me. However the answer was in front of me the entire time: GetForCURRENTVIEW.

Windows 8 apps can be built in one of two ways:

  • Page Model – This is the same model as Windows Phone 7 where when you want a new UI you navigate to entire new page, or view.
  • Composition Model – In this model you have a single page, and you inject content in the form of user controls into the page. I am working with AtomicMVVM which follows this pattern.

The problem with the composition model, is that the events are tied to the page (or view) & since I never changed the page (just the content was swopped in and out), the event handlers were never being changed.

The solution for me was to make it possible for the view models to state if they have Share or Settings and then have a single place in the constructor to setup the configuration for the charms. I used a simple interface based system for this which the following code should illustrate. Since the event handler was attached once – the exception went away. This also allows my view to be very smart about the share & settings events and what it passes to those.

// during the startup I bind once to the event. Note that I onlt do this once the UI is up.
    bootstrapper.AfterStartCompletes += () =>
            SettingsPane.GetForCurrentView().CommandsRequested += SettingCommandsRequested;

void SettingCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
    var settings = Bootstrapper.CurrentViewModel as ISettings;

    // if the view model implements the interface then I can call the method to set the commands it needs.
    if (settings != null)

For a complete example of this see the Metro Demo in the AtomicMVVM samples: MetroDemo


Windows 8 Developer Links – 2012-09-27 | Dan Rigby's picture

[...] drop that into your favourites if you’re going to be working with this API set…”Windows 8 Development Snack: InvalidOperationException for Share & Settings (Robert MacLean)“With one of my earliest apps I kept having a problem with a COM exception [...]

 Windows 8 Development Snack: InvalidOperationException for 's picture

[...] Read original post at Robert MacLean's Blog [...]

Add new comment