How to format DataGrid rows based on data's units

171 Views Asked by At

I have a DataGrid with a collection of parameters, each of which have properties for name and a value. Each parameters' value can be one of a multitude of units (ft, btuh, kw, currency, string, unit less double, etc.) How do I format the data grid rows to display the value with the units and a unit dependent rounding factor? See below for an example.

Example DataGrid

The DataGrid can reference different object classes with different collections of parameters so the solution has to be dynamic. Maybe add a Units enum to the parameter class and then somehow read that from the DataGrid and format the row accordingly?

1

There are 1 best solutions below

0
Albert Alonso On

One approach I would take would be make a converter. I've made you one just to pitch the idea but you should probably modify it to suit your needs.

public class CellUnitConverter : MarkupExtension, IValueConverter
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }

    public string Unit { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //Checks both if the value is null or if the converter somehow gets used ahead of time
        if (value == null || value == DependencyProperty.UnsetValue)
        {
            return string.Empty;
        }

        // You can place some rounding rules here

        return $"{value} {Unit}";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

As it uses the MarkupExtension, you can just place it in the binding of the cell

Binding="{Binding Results, Converter={converters:CellUnitConverter Unit=CFM}}"

However, if you want different units depending on the value, you could also Bind the unit to another property such of each element.

Let's you are displaying a collection of DataItem where each one has a Title, Result,Unit. Then, you bind one column to the Title and the other one to the Result, such like

Binding="{Binding Result, Converter={converters:CellUnitConverter Unit={Binding Unit}}}"

Hope this points to the solution.