Archive for June, 2017

Fun with C#: Adding visual behavior to dynamic view model

As promised on my previous post, let’s see how we can add a nice little feature that leverages the capabilities of the DynamicDtoDecorator we’ve been creating across several blog posts. The gist of this feature is to add dynamic properties to the view model to help support a “dynamic background color” behavior for the data properties that need it.

As an example, let’s take a screen that has some data grid similar to this:

Now, let’s pretent there’s a requirement where the cell background must be green when a product name is “banana”, and yellow for anything else:

Of course, the background has to change accordingly when the user changes the product name on the screen.

Adding to the example, let’s say that the category cell background color must change based on the category:

And finally, the total cell background must also change… however, it also depends on the category, and it uses different colors:

If you’ve been following my series on “How to get rid of INPC using Dynamic” (starting here), you know my example app here uses a DynamicDtoDecorator that takes a POCO ViewModel, enhances it with INPC behavior, and is then bound to the view. Using that decorator we can tap into WPF’s databinding features to make it easier to expose this visual behavior we want for the data.

The main idea here is the following: the ViewModel already contains the data that we want displayed on the UI. We can then use the decorator to enhance the ViewModel to help the view display that data.

I’ll walk you through how I’ve implemented this type of feature in this sample app. Bear in mind this is a much trim down version from a real world, much larger, app that I’ve worked on a while ago. I’ll point out the main differences between the sample and the real app when appropriate.

In order to support visual aspets for the InvoiceItemViewModel class, I’ve created a class named InvoiceItemVisuals, starting it off like this:

public class InvoiceItemVisuals
{
}

I’ve then added a method specifically to define the cell background definitions for an invoice item:

public IEnumerable<cellbackgrounddefinition> GetCellBackgrounds()
{
    yield return new CellBackgroundDefinition("ProductName",
        new [] { "ProductName" }, 
        vm => vm.ProductName == "Banana",
        new Dictionary
        {
            {true, Brushes.Green},
            {false, Brushes.Yellow}
        });
    yield return new CellBackgroundDefinition("Category",
        new[] { "Category" },
        vm => vm.Category,
        new Dictionary
        {
            {"1", Brushes.LightBlue},
            {"2", Brushes.LightGray},
            {"3", Brushes.LightSalmon}
        });
    yield return new CellBackgroundDefinition("Total",
        new[] { "Category" },
        vm => vm.Category,
        new Dictionary
        {
            {"1", Brushes.Red},
            {"2", Brushes.Pink},
            {"3", Brushes.Purple}
        });
}

</cellbackgrounddefinition

The CellBackgroundDefinition is a generic class that expects to know the type of ViewModel it works with, and takes in four important pieces for it to work:

  1. The name of the data property bound to the cell;
  2. A list of dependent properties. For instance, the background color for the total cell depends on the value of the category;
  3. A Func that takes in an instance of the ViewModel, and returns whatever gives the value that’ll be used to determine the cell background color. In the example above, we’re interested on the value of Category; 
  4. A dictionary indicating the colors to be used for each expected value (in the example above, “1” is red, “2” is pink, “3” is purple.

Real World: the application in the real world didn’t have those definitions set in code; instead, those were all stored in the database, with support to have both default settings that shipped with the app, as well as user overrides.

Once we have those “background definitions” specified, we have to inject them into our decorated DTO (in our case, the view model). For that, I’ve added an InjectInto method to the InvoiceItemVisuals class:

public void InjectInto(DynamicDtoDecorator decoratedDto)
{
    GetCellBackgrounds().ForEach(definition =>
    {
        var backgroundProperty = {0}#x22;{definition.PropertyName}_Background";
        decoratedDto.RegisterPropertyDependencies(backgroundProperty, definition.DependsOn);
        decoratedDto.Register(backgroundProperty, () => definition.Func(decoratedDto.GetDto()), newValue => {});
    });
}

The method takes in the DynamicDtoDecorator, goes through all the cell background definitions, and register those as dynamic properties and their dependencies. As mentioned before, the new property is named after the data property it refers to, and it has a “Background” suffix, so for the Category background, we’ll have a “Category_Background” property.

Notice that the Register method on the DynamicDtoDecorator takes in the name of the new property, as well as Funcs for the property’s getter and setter. Our getter in this case simply calls the Func that is part of the background definition (which, for the Category background looks like vm => vm.Category), whereas the setter doesn’t really need to do anything.

The final piece for this feature to work is to set things up in the UI so it knows how to use our dynamic properties. Please, remember this is a WPF application, so we can create styles and triggers to handle the visual stuff. Instead of defining those declaratively in XAML, we do it imperatively in C#. To keep things simple in this sample app, I’ve added a ConfigureDataGrid to my InvoiceView Window class, which in turn calls a ConfigureCellBackgrounds method, and this is the guy who does the heavy lifting here:

private void ConfigureDataGrid()
{
    var modelVisuals = new InvoiceItemVisuals();
    ConfigureCellBackgrounds(modelVisuals);
}

private void ConfigureCellBackgrounds(InvoiceItemVisuals modelVisuals)
{
    var cellsBackgrounds = modelVisuals.GetCellBackgrounds();

    cellsBackgrounds.ForEach(cellDefinition =>
    {
        var column = (DataGridTextColumn) ItemsGrid.Columns
            .Single(c => c.Header.ToString() == cellDefinition.PropertyName);
        var style = new Style(typeof(TextBlock));

        cellDefinition.TriggerDefinitions.ForEach(trigger =>
        {
            var binding = {0}#x22;{cellDefinition.PropertyName}_Background";
            var propertyValue = trigger.Key;
            var propertyBackground = trigger.Value;
            var dataTrigger = new DataTrigger
            {
                Binding = new Binding(binding),
                Value = propertyValue
            };
            dataTrigger.Setters.Add(new Setter
            {
                Property = TextBlock.BackgroundProperty,
                Value = propertyBackground
            });
            style.Triggers.Add(dataTrigger);
        });

        column.ElementStyle = style;
    });
}

Breaking down the implementation of ConfigureCellBackgrounds, here’s what we do:

  1. Get the cell background definitions and loop through them;
  2. Get a reference to the GridColumn that hosts the data cell we’re interested in;
  3. Go through the TriggerDefinitions;
  4. Set up the Binding expression so it points to the appropriate “Cell_background” property;
  5. Put the binding expression in a DataTrigger for the TextBlock.BackgroundProperty;
  6. Put the data trigger in a new style created for TextBlock (where the values are displayed on the UI);
  7. Set the style on the grid column.

Done.

If you’d like to check out this sample app in action, here’s a link to the repo in GitHub:

Dynamic Decorator

Once again, bear in mind that this sample app shows a very simplified version of a full-blown Real World app that used this approach extensively. In the full app, a lot of the implementation went into a custom framework, and expressions and definitions for visual things and behaviors were specified both in C# code (for the options shipped with the application) and stored in the database (for the options overridden by specific clients and users).

I’ve used this approach successfully in at least two other projects, and will probably keep it in mind to use again if appropriate. 🙂

Advertisements

Leave a comment

Come checkout the new Improving Houston office

We are celebrating the opening of our newly designed office space. We would love for you to join us On Thursday, June 15th from 4pm to 7pm. We will have the Houston West Chamber of Commerce in attendance for the ribbon cutting. Come out and see what Improving is all about. Please register here

 https://improvinghoustonribboncutting.eventbrite.com

Leave a comment

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:

decorator.ProductName_Background

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