Proper pattern for defining collection type Dependency Properties?

April 23, 2010

I’ll relate a query that I recently posted on the Silverlight forums here, in case someone reading this has a good answer:

So, we all know that when creating a Dependency Property that has a collection type that setting a new collection instance as the default value in the metadata does not have the desired effect as that instance will be shared between all instances of the class as the default value of that property. So the correct solution is to initialize the collection instance in the constructor, see

But what if you want to set a value for this collection via a style? Or set its default value in the default style? For an example, see the Palette property on the Silverlight Toolkit chart. If we provide a value locally in the constructor, this will take precedence over the value provided in the style correct? Or if we avoid initializing the collection in the constructor, as in the Palette example, then this will not work:

   <CollectionItem />
   <CollectionItem />

only this will:

       <CollectionItem />
       <CollectionItem />

So, if you need a collection property to be stylable you can avoid setting it in the constructor and document that when used in xaml it needs a new collection instance to be instantiated. But what happens when tools like blend blithely create the former xml snippet when you use their collection editor?

Does anyone know a good pattern that allows for all these behaviors?


Dynamically generating types to implement INotifyPropertyChanged

April 13, 2010

As I mentioned in my last post, so much in Silverlight/WPF (especially when using MVVM) requires INotifyPropertyChanged for smooth operation that it would really be nice if there were first-class language support for augmenting classes in this way. INotifyPropertyChanged is pretty easily classified as a cross-cutting concern, I believe, and hence is a natural fit for aspect oriented programming techniques. For example, if its in your toolbelt, you could use Postsharp to do it pretty neatly, or other similar tools.

But, what I’m interested in, is if you want some simple code to implement this that stands alone and doesn’t have any external dependencies on 3rd party libraries, what would that look like? And how complicated is that? I was hoping to be able to use the new support for LambdaExpression.CompileToMethod in .NET 4 to make my life easier and avoid having to directly emit IL code, but it seems this API has some limitations (its only usable to generate static methods) at the moment that would prevent it being used in this manner. So, unfortunately, a degree in IL authoring is required to understand the code I’ll relate below.

The basic concept is that we will dynamically generate a type that inherits from the type for which we want to implement INotifyPropertyChanged. It will override the setters of any public or protected virtual properties, and raise the PropertyChanged event with the property name after the base setter has been called. This derived type implements the INotifyPropertyChanged event and is the actual type that you will create an instance for.

Things to note with this approach:

  1. This does not attempt to “wrap” a live instance of the class you trying to augment with the interface. It instead creates a derived type that you should instantiate rather than the actual type. This approach could be modified to wrap a live instance without too much additional effort.
  2. The implementation is not yet thread-safe.
  3. This approach relies on the public properties being marked as virtual so that they are overridable in the dynamically generated type.
  4. As I’m not actually using this code (its mostly an experiment, currently), it is a bit rough, so use at your own risk, and you may need to do some polishing, but this could act as a jumping off point if you are interested in this kind of approach, or or trying to learn more about runtime IL generation.
  5. This was written against the Silverlight subset of the Framework, so should work fine against Silverlight or WPF.

Let’s start with how you can use the code. If we have a class, Test:

public class Test
    public virtual double TestDouble { get; set; }
    public virtual string TestString { get; set; }

We can create an instance of it and use it in this way:

Test testObj = ProxyProvider.Instance.NewProxy<Test>();
(testObj as INotifyPropertyChanged).PropertyChanged +=
    (o, e) => System.Diagnostics.Debug.WriteLine(
    "property changed: " + e.PropertyName);
testObj.TestDouble = 5;
testObj.TestString = "testtest";

And when we run the application, the debug statements confirm that the property changed events are firing. So, how is this accomplished?

Let’s start with the rather boring singleton that furnishes the augmented types:

public class ProxyProvider
        private static volatile ProxyProvider _instance = null;
        public static ProxyProvider Instance
                if (_instance == null)
                    _instance = new ProxyProvider();
                return _instance;

        private ProxyProvider()

        private Dictionary<Type, Type> _proxyTypes = new Dictionary<Type, Type>();

        public T NewProxy<T>()
            return (T)ProxyHelper(typeof(T));

        private object ProxyHelper(Type type)
            Type proxyType;
            if (_proxyTypes.TryGetValue(type, out proxyType))
                return Activator.CreateInstance(proxyType);
                proxyType =
                _proxyTypes.Add(type, proxyType);
                return Activator.CreateInstance(proxyType);

        public object NewProxy(Type type)
            return ProxyHelper(type);

This basically just maintains a dictionary of generated types so they don’t need to be generated anew each time. The real work of the dynamic type generation is occurring in the INotifyPropertyChangedProxyTypeGenerator:

public class INotifyPropertyChangedProxyTypeGenerator
        private static AssemblyBuilder _ab;
        private static ModuleBuilder _mb;

INotifyPropertyChangedProxyTypeGenerator needs some Reflection.Emit objects that aid in the construction of dynamic types. The AssemblyBuilder manages the dynamic assembly we are creating in memory, and the ModuleBuilder manages the module that will contain our types.

        public static Type GenerateProxy(Type type)
            if (_ab == null)
                var assmName = new AssemblyName("DynamicAssembly");
                _ab = AppDomain.CurrentDomain.DefineDynamicAssembly(
                _mb = _ab.DefineDynamicModule(assmName.Name);

            // public class [TypeName]__proxy
            //    : [TypeName], INotifyPropertyChanged
            TypeBuilder typeBuilder = _mb.DefineType(
                type.Name + "__proxy", TypeAttributes.Public, type);

            FieldBuilder eventField =

            MethodBuilder raisePropertyChanged =
            CreateRaisePropertyChanged(typeBuilder, eventField);

            // get all the public or protected
            // virtual property setters.
            var props = from p in
                                BindingFlags.Public |
                                BindingFlags.NonPublic |
                                BindingFlags.Instance |
                        where p.GetSetMethod().IsVirtual &&
                        (p.GetSetMethod().IsPublic ||
                        select p;
            (item) => WrapMethod(
            item, raisePropertyChanged, typeBuilder));

            Type ret = typeBuilder.CreateType();
            return ret;

This is the top level script of actions that are required to generate the dynamic type:

  1. Assert that our AssemblyBuilder and ModuleBuilder are created.
  2. Create the dynamic type based off the original type’s name.
  3. Cause the new type to implement the interface INotifyPropertyChanged.
  4. Create the PropertyChanged event on the new type to implement the interface.
  5. Create a method on the new type called RaisePropertyChanged, which will be called from the property setters.
  6. For each public or protected virtual property, override the setter method, having each new setter call RaisePropertyChanged.
  7. Return the created type.

Now, let’s drill down further into how these steps are accomplished. First, let’s see how we create the PropertyChanged event:

        private static FieldBuilder CreatePropertyChangedEvent(
        TypeBuilder typeBuilder)
            // public event PropertyChangedEventHandler PropertyChanged;

            FieldBuilder eventField =
            EventBuilder eventBuilder =

            CreateAddRemoveMethod(typeBuilder, eventField, true));
            CreateAddRemoveMethod(typeBuilder, eventField, false));

            return eventField;

The event consists of the actual event definition which has an Add method and a Remove method that indicate what occurs when users += or –= the event, and the delegate that will store the delegate chain associated with the event. This method will create the event and backing delegate definitions on the type, and then create the add and remove methods for the event by calling this method:

 private static MethodBuilder CreateAddRemoveMethod(
            TypeBuilder typeBuilder, FieldBuilder eventField, bool isAdd)
            string prefix = "remove_";
            string delegateAction = "Remove";
            if (isAdd)
                prefix = "add_";
                delegateAction = "Combine";
            MethodBuilder addremoveMethod =
            typeBuilder.DefineMethod(prefix + "PropertyChanged",
               MethodAttributes.Public |
               MethodAttributes.SpecialName |
               MethodAttributes.NewSlot |
               MethodAttributes.HideBySig |
               MethodAttributes.Virtual |
               new[] { typeof(PropertyChangedEventHandler) });
            MethodImplAttributes eventMethodFlags =
                MethodImplAttributes.Managed |

            ILGenerator ilGen = addremoveMethod.GetILGenerator();

            // PropertyChanged += value; // PropertyChanged -= value;
            ilGen.Emit(OpCodes.Ldfld, eventField);
                new[] { typeof(Delegate), typeof(Delegate) }),
            ilGen.Emit(OpCodes.Castclass, typeof(
            ilGen.Emit(OpCodes.Stfld, eventField);

            MethodInfo intAddRemoveMethod =
            prefix + "PropertyChanged");
            addremoveMethod, intAddRemoveMethod);

            return addremoveMethod;

The add or remove method are constructed using the following steps:

  1. Create the method named add_PropertyChanged or remove_PropertyChanged. A good trick for determining method attributes or implementation flags (or method body for that matter) if you are unsure is to write what you are trying to emulate in c# and compile it, and then use Reflector to examine the IL code that was generated.
  2. Emit code that adds or removes the provided delegate to the backing delegate chain for the event.
  3. Specify that the method is overriding the expected method on the INotifyPropertyChanged interface.
  4. Return the resulting method.

The RaisePropertyChanged method we create will simply call the delegate chain backing the PropertyChanged event if it is non-null:

private static MethodBuilder CreateRaisePropertyChanged(
TypeBuilder typeBuilder, FieldBuilder eventField)
            MethodBuilder raisePropertyChangedBuilder =
                MethodAttributes.Family | MethodAttributes.Virtual,
                null, new Type[] { typeof(string) });

            ILGenerator raisePropertyChangedIl =
            Label labelExit = raisePropertyChangedIl.DefineLabel();

            // if (PropertyChanged == null)
            // {
            //      return;
            // }
            raisePropertyChangedIl.Emit(OpCodes.Ldfld, eventField);
            raisePropertyChangedIl.Emit(OpCodes.Brtrue, labelExit);

            // this.PropertyChanged(this,
            // new PropertyChangedEventArgs(propertyName));
            raisePropertyChangedIl.Emit(OpCodes.Ldfld, eventField);
                .GetConstructor(new[] { typeof(string) }));
                .GetMethod("Invoke"), null);

            // return;

            return raisePropertyChangedBuilder;

If you are new to IL generation and mostly use C#, the way that the if statement unrolls into, basically, a goto may be new to you. Although much more advanced, IL code is in many ways very similar to Assembly language due to the need to translate IL code into native code very efficiently. The IL code emitted here will check to see if the delegate chain associated with PropertyChanged is null in which case it will branch to the exit label and skip the invocation of the delegate chain.

Last but not least, here is how we will override each setter, call its base implementation and then call RaisePropertyChanged:

        private static void WrapMethod(PropertyInfo item,
        MethodBuilder raisePropertyChanged, TypeBuilder typeBuilder)
            MethodInfo setMethod = item.GetSetMethod();

            //get an array of the parameter types.
            var types = from t in setMethod.GetParameters()
                        select t.ParameterType;

            MethodBuilder setMethodBuilder = typeBuilder.DefineMethod(
                setMethod.Name, setMethod.Attributes,
                setMethod.ReturnType, types.ToArray());
            setMethodBuilder, setMethod);
            ILGenerator setMethodWrapperIl =

            // base.[PropertyName] = value;
            OpCodes.Call, setMethod, null);

            // RaisePropertyChanged("[PropertyName]");
            setMethodWrapperIl.Emit(OpCodes.Ldstr, item.Name);
            OpCodes.Call, raisePropertyChanged, null);

            // return;

The steps involved are:

  1. Create the method using the same settings of the Set method we are overriding.
  2. Emit IL that calls the base setter method.
  3. Emit IL that calls the RaisePropertyChanged method passing in the name of the current property.

And that’s basically it! We’ve created a dynamic assembly, a dynamic module and a dynamic type that inherits from the target type, but also implements INotifyPropertyChanged, and overrides any overridable setters and has them raise the PropertyChanged event! Pretty neat huh?

So what’s next? I’m somewhat satisfied with this because it employed a self contained and small amount of code to massively reduce the amount of boilerplate needed if you have a lot of types that need to implement this interface. But, really, it can be a bit too onerous or ill-advisable to absolutely require that properties be overridable to take advantage of this (not to mention error-prone!). So I think I’ll investigate what methods I might use to rewrite IL in an assembly as a post-compile step to improve on all this. The obvious and easiest choice is to use PostSharp to do this kind of IL rewriting, but as I and others are not always in a position to leverage 3rd party tools, I’m interested in how complex a stand-alone solution would be.

Well, until next time 😉

INotifyPropertyChanged language support, please.

March 30, 2010

When using patterns such as MVVM, and, well, using WPF and Silverlight in general, INotifyPropertyChanged is so prevalent that I think it really merits native language support. You could use AOP or code gen to cut out the boiler plate. But if you are say, sharing a WPF or Silverlight code sample it would be darn nice to not have to have external dependencies just to write some elegeant Silverlight/WPF code.

Windows Phone + Silverlight/XNA = Awesome

March 5, 2010

Awesome 🙂

HP MSS (WHS) Upgrade to release in December

October 9, 2009

Excellent. We, the consumers, told HP we would even be willing to pay if we could only get access to their excellent software upgrades for the older Mediasmart lines, and it looks like they are doing the smart thing and converging the platform at version 3.0. Excellent HP, thanks for listening!

The problem with HDMI handshaking

August 29, 2009

I had the most difficult time last night trying to upgrade to OSX Snow Leopard. I performed the upgrade and was presented with a blank screen when my mac mini rebooted. I assumed that my resolution had been changed to some mode my television didn’t support so I tried all sorts of things to try and right the situation, but even booting into safe mode resulted in a black screen.

After hours of trying to work out a way to force the mac mini to use a more sane default resolution on boot I finally thought to pull out the hdmi switch I was using and connect the mini directly to the tv. And low and behold, I had video. My tv was obviously broadcasting that it was capable of 1080p, but either a bad switch or cable was reducing the hdmi bandwidth to the point that the resulotion was not actually possible.

So, the HDMI handshaking process seems pretty flawed to me, there should be some way the source can test different modes, and the destination should be able to report success or failure of different modes. A simple capabilities list simply isn’t cutting it. That and its pretty deplorable that apple often makes things WAY TO HARD by making them so simple. Why should SAFE MODE try to probe for capabilities of the destination device instead of picking a SAFE resolution to display in, and why should an OS upgrade try to pick a new resolution than the one I had manually selected? (1080p is a bit hard to read on my TV).

The other unexplained mystery is why my pc (and osx 10.5) could display 1080p content to the tv through this same switching hardware but snow leopard can’t? A bit boggling, to be honest.

Facebook: Guilty until proven innocent?

August 28, 2009

So my facebook account still hasn’t been reinstated, but finally received an email from them. They apparently think I’m fake, for whatever reason. I’m guessing some automated heuristic? Or maybe some jerk reported me as fake? Either way my account has been diasabled for weeks before they even gave me the chance to defend my existence, not even knowing what I was accused of. Pleasant. I have tried to offer them what proof of identity I can without violating my privacy, so the ball is in their court. Am I real?!?! If not my siblings and wife that are my facebook friends better watch out! They must be fake too!!!