Archive for category WPF

Fun with C#: Enhancing ViewModels with a Dynamic Decorator

I’ve been posting a series on how to use C# Dynamic Features in order to get rid of implementing INotifiyPropertyChanged (INPC) on my ViewModels. If you’ve been following those posts, you’ll notice that the class I created to enable this is called DynamicDtoDecorator.

That class initially started as a proxy, simply bridging access to the properties on the internal object. After I added the INPC support to it, it really became a decorator. But I really started leveraging its abilities as a decorator when I started injecting more properties into the object in order to support more visual behavior.

As I mentioned back in this post, I wanted to leverage WPF’s data-binding capabilities. Using those capabilities to simply show data on the screen is really just the tip of the iceberg; the framework also allows binding to be used to do things like controlling visibility of UI elements, change visual aspects for elements (for instance, changing the background color of a grid cell), etc.

In this post, we saw that we can use the decorator like so:

var viewModel = new InvoiceItemViewModel { ProductName = “Some value" };
dynamic decorator = new DynamicDtoDecorator(viewModel);

We can then bind UI elements to the ProductName property, which is exposed through the decorator. Now, maybe we have some requirement that indicates the background where we show product name should change based on some data (which could potentially be changed by the user). It’d be handy to have a property on object like so:


Usually, property names in C# classes don’t have an “_”, but I do that as a simple convention so it makes it easy to parse it out and know the “data” property and the visual aspect we’re talking about there. Also, bear in mind that in the real world app where I’ve used this approach nobody would be accessing those properties directly in code: each property gets added dynamically to the decorator, and the all the data-binding is also hooked up dynamically.

In the next post we’ll see how we make the main part of that actually happen.

Leave a comment