Subscribe to the RSS feed then follow me on twitter at @mrlacey

Wednesday, March 16, 2011

Binding to static classes in Windows Phone 7

It's a common request to be able to bind to a global variable in various parts of an application. It's often common that such variables are static.
This question seems to pop up in forums rather regularly and often the advice given is that this isn't possible or to include the "global" variable as part of the model being used as the DataContext of the page. Such duplication of functionality in the model is a bad idea and totally unnecessary.

It's not possible to bind to a static class as binding requires an object instance.
You can, however, bind to static properties of a class.

So we can bind to the static properties of the following.

namespace StaticBinding
  public class MyStaticClass
    private static string myStaticProperty = "my static text";

    public static string MyStaticProperty
      get { return myStaticProperty; }
      set { myStaticProperty = value; }

We can then create an application level resource which we can actually bind to:

.. xmlns:myns="clr-namespace:StaticBinding"


(Sorry, don't know why the syntax highlighter has forced upper case - I'm sure you're smart enough to work out what should and shouldn't be upper case though. ;)

With the above configured we can then bind to our global property in any page we wish. We just need to set the `Source` and `Path` of the binding.



A nice upside of this is that you even get intellisense on the `Path`. (Assuming you've set the `Source` first.)


If you've built Windows Phone or Windows Store apps you can cross-promote them with AdDuplex to get more users.

1 comment: