Writing Clone-friendly Binding Elements

When writing a custom binding element, you will notice two constructors on the abstract base class:

protected BindingElement()
protected BindingElement(BindingElement elementToBeCloned)

The usage of the first (default) constructor is straightforward. The second one, which takes a BindingElement is a little more subtle. Its purpose is to facilitate proper implementations of BindingElement.Clone(). The recommended pattern is that all non-sealed binding elements expose such a protected ctor, and then call that ctor from their Clone() method. This allows subclasses of your binding element to be able to implement Clone in a chained manner (since you can’t just call base.Clone()). In other words, if I was writing a FooBindingElement, my Clone() method would leverage this constructor as follows:

protected override BindingElement Clone()
return new FooBindingElement(this);

If you then set a breakpoint on your Clone() method, you will see it called a bunch of times when you open a Client or Service. The reasons behind this have to do with the tension between the assurances we can (or cannot make) about side-effects of certain methods and needing to ensure the integrity of the original configured binding. Reading back over that last sentence, it probably sounds a bit obtuse. I’ll try and clarify/go into more details around our CanBuild, Build and GetPropery processes (prime users of Clone) in a future post.

Leave a Reply

Your email address will not be published. Required fields are marked *