Monthly Archives: April 2011

Managing WP7 UI state with Caliburn.Micro’s guard conditions

My first Windows Phone 7 app had a lot of extraneous code whose sole purpose was enabling and disabling pieces of the user interface. Managing the visual state of buttons was one pain point. I ended up with a lot of code that looked like this:

private void ToggleButtons()
    if (timer.Status == "running")
        StartButton.IsEnabled = false;
        EndButton.IsEnabled = true;

    else if (timer.Status == "stopped")
        StartButton.IsEnabled = true;
        EndButton.IsEnabled = false;

There are about 20 things wrong with that example, but the one I’d like to focus on is how poorly conditional checks like this scale. It’s manageable when I have two buttons, but what if I had 10? Add in a third status code and the code balloons to dozens or even hundreds of lines in a hurry. (While this article focuses on MVVM, if you want to reimplement that example more elegantly in a traditional codebehind style, leave a comment. I’d be interested to see what you come up with.)

The Caliburn.Micro MVVM framework provides an elegant means for handling this scenario. Rather than setting a button’s enabled state manually, Caliburn.Micro allows you to create a boolean property that indicates whether a button can perform its intended function. If the button’s operation can’t successfully execute, the button itself is automatically disabled. Let’s look at a simple example.

Overview of the sample

The sample app illustrates how to implement a common scenario:

  • MainPage.xaml includes a textbox, a textblock and a button.
  • As long as the textbox is empty, the publish button is disabled.
  • When the user enters text in the textbox, the publish button is automatically enabled.
  • Clicking the publish button displays the entered text in the textblock

Dead-simple databinding

Here’s the entire view, minus some boilerplate and formatting attributes:

<Grid x:Name="LayoutRoot">
    <Grid x:Name="ContentGrid">
        <StackPanel >
            <TextBlock Name="PublishedText"/>
            <TextBox Name="TextToPublish" />
            <Button Content="Publish"
                    Name="Publish" />

I’m using Caliburn.Micro’s convention-based databinding to link the three elements in my UI to properties in the page’s viewmodel. In this case, it’s simply a matter of applying a Name attribute to each element that corresponds to a property or method name in the viewmodel. Caliburn.Micro wires them up automatically.

Properties, action messages and guards

The heavy lifting, such as it is, happens in the viewmodel:

public class MainPageViewModel : PropertyChangedBase
    private  string textToPublish;
    public string TextToPublish
            return textToPublish;
            textToPublish = value;
            NotifyOfPropertyChange(() => CanPublish);

    public bool CanPublish 
            if (string.IsNullOrEmpty(TextToPublish))
                return false;
                return true;
    public string PublishedText { get; set; }

    public void Publish()
        PublishedText = TextToPublish;
        NotifyOfPropertyChange(() => PublishedText);

There are several key elements to this viewmodel. First, note that MainPageViewModel inherits from PropertyChangedBase, which is Caliburn.Micro’s base class implementation of INotifyPropertyChanged. The NotifyOfPropertyChange method is defined in PropertyChangedBase. Which brings me to the second important element…

The NofityOfPropertyChange calls are what tell the view that something has changed and trigger it to update itself. In this case, the TextToPublish property is updated automatically when the user enters text into the databound TextToPublish textbox. The property’s setter then pokes the view and tells it to reevaluate CanPublish.

CanPublish is what is known as a CanExecute guard condition. A guard condition is a boolean property that is paired via a naming condition to a method in the viewmodel. If the guard returns false, it blocks the method from executing, and the corresponding UI element is disabled until the CanExecute condition evaluates to true.

To implement a guard, create a boolean property and append the word Can to the beginning of the method name that the guard is associated with. In the example, CanPublish is guarding the Publish method, which is linked to the Publish button in the view.

TextToPublish kicks the view to check CanPublish, which evaluates whether any text exists in TextToPublish. If the property contains text, CanPublish returns true, and the publish button lights up to let the user know that the button is enabled.

Download the sample

A complete Visual Studio project that implements the example above is available at my Codeplex site. It was built with the February 2011 version of the Window Phone Developer tools. Other than the WP7 tools, there are no external dependencies. The Caliburn.Micro framework code is included in the Framework folder.


Leave a comment

Filed under Caliburn.Micro, MVVM, Windows Phone 7

Using display ads in Windows Phone 7 apps

Enabling display ads in a Windows Phone 7 app is a three-step process:

  1. Installing the Microsoft Advertising SDK.
  2. Registering the application with the Microsoft pubCenter.
  3. Embedding the ad control in the application.

Installing the SDK

The Microsoft Advertising SDK is available on the Microsoft Advertising site. The SDK is an .msi installer file, and executing it copies several .dlls and help files to the program files directory. On my PC the files are located in:

C:\Program Files (x86)\Microsoft Advertising SDK for Windows Phone 7

Registering the app

There are two main goals in the registration process:

  1. Subscribing your app to several ad channels that will be relevant to the app’s users.
  2. Obtaining unique ad unit and application IDs. These ties your app to the channels you select and are used to track the number of impressions your app generates.

To register your app:

  1. Visit the Microsoft Advertising pubCenter and either create a new account or use your existing Microsoft Live account to sign in.
  2. Click Setup, then Register. Enter your app’s name and click Save. Your app will appear under the Sites & apps tab. Notice the application ID; you’ll need it later.
  3. Click Ad unit, then select Create a new application ad unit.
  4. Enter a name for the ad unit, then select up to three categories. These determine the types of ads your users will see, so choose categories that seem relevant.
  5. Click Save. Note the ad unit ID; you’ll need this one later as well.

Embedding the ad control

Before you can implement the ad control in your app, you need a reference to Microsoft.Advertising.Mobile.UI, which you can add by right-clicking on the References folder in the Solution Explorer, then clicking Add Reference. Browse to the advertising SDK folder and select the Silverlight .dll.

Open the XAML page that will hold your ad control, and add an XML namespace for the advertising assembly:

<phone:PhoneApplicationPage x:Class="Wp7AdControlSetup.MainPage"

Next, insert the ad control itself into your XAML page:

<advertising:AdControl ApplicationId="test_client"

The ad control is now installed and set up to run in test mode.

Test mode vs. production mode

When the ad control is configured for test mode, you should see something like this when you run the app in the emulator:

Test ads

Sometimes the ads take a few seconds to start loading, but if you don’t see anything after a minute or two, something is set up incorrectly.

You can also view live ads in the emulator and on your unlocked device before publishing your app to the Marketplace. Production ads look like this:

Live ads

Switching the ad control to show live ads involves adding production ad and unit IDs to the control’s XAML and disabling test mode for your application. First, add the app and ad unit IDs that you received during the pubCenter registration process to the advertising control:

<advertising:AdControl ApplicationId="3a6a7b1b-3b66-4fa0-9732-514fc9aa8b89"
                       AdModel="Contextual" />

Next, open up the App.xaml.cs file and add the following code in the public App() constructor, beneath the InitializeComponent() method:

public App()

    AdControl.TestMode = false;

Failing to set the AdControl.TestMode early enough in the application’s lifecycle will cause the ad control to load an empty frame. Setting it in the application’s constructor ensures that it is set before the control itself is rendered.

If you want to revert to test ads, reinsert the test app and ad unit IDs and remove the line that sets AdControl.TestMode = false.

Download the sample

A full working example is available on my CodePlex site. The sample includes real ad unit and application IDs so you can see live ads in the emulator. It was built with the February 2011 version of the Windows Phone developer tools. A reference to the advertising .dll is included, but you will probably need to relink the .dll to your local copy of the advertising SDK.

1 Comment

Filed under Windows Phone 7

New Visual Studio extension for debugging XAML databinding expressions

A subgroup of the Windows Phone 7/Silverlight team, headed by Jeff Wilcox, just released an extension for Visual Studio 2010 that takes the pain out of debugging XAML databinding expressions.

The extension, which Microsoft marketing has awkwardly dubbed the Productivity, Refactoring And Notification Konnector, allows you to set breakpoints in your XAML and see what values are being applied at runtime.

Quick look

Using the extension is simple. Just set a breakpoint in your XAML page like you would in C#. As you can see, Visual Studio hits the breakpoint, and you can explore the bound properties or collection.

The new Visual Studio XAML debugger takes the pain out of databinding.

The Productivity, Refactoring And Notification Konnector add-in was released 4/1/2011.


Filed under Windows Phone 7