5
votes

I'm trying to create a style for the DataGrid cells in my application. I thoight that maybe there is a way to right align the numeric cells in DataGrid using a DataTrigger. Is this even possible?

My style for my DataGrid is this:

<Style TargetType="{x:Type DataGrid}">
    <Setter Property="AlternatingRowBackground">
        <Setter.Value>
            <SolidColorBrush Color="#CCCCCC" />
        </Setter.Value>
    </Setter>
    <Setter Property="CanUserAddRows" Value="False" />
    <Setter Property="CanUserDeleteRows" Value="False" />
    <Setter Property="Background">
        <Setter.Value>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                <GradientStop Offset="0" Color="#CCCCCC" />
                <GradientStop Offset="1" Color="#FFFFFF" />
            </LinearGradientBrush>
        </Setter.Value>
    </Setter>
    <Setter Property="RowHeaderWidth" Value="0" />
    <Setter Property="CellStyle">
        <Setter.Value>
            <Style TargetType="{x:Type DataGridCell}">
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="Background">
                            <Setter.Value>
                                <SolidColorBrush Color="#7777FF" />
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Setter.Value>
    </Setter>
</Style>

I'm thinking of maybe adding some kind of trigger on the CellStyle to detect if the content is numeric (int, double, decimal,...) and style the cell accordingly. Is this possible?

Update

Thinking about this I've tried several things, but it didn't work. I tried using a DataTrigger defined as:

<DataTrigger Binding="{Binding Converter={StaticResource IsNumericConverter}}" Value="True">
    <Setter Property="HorizontalContentAlignment" Value="Right" />
</DataTrigger>

Where IsNumericConverter is:

public class IsNumericConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value is int || (value is decimal || value is double);
    }

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

But when I set a breakpoint on the converter I get that the value is of the type of the whole row, not each individual cell...

3

3 Answers

3
votes

One way to do this is to set up the triggers in code-behind. The following method applies a trigger to a DataGridColumn. This trigger uses your IsNumericConverter to determine whether to do the right-alignment:

    public static void AddTriggerToColumnStyle(DataGridColumn column)
    {
        var boundColumn = column as DataGridBoundColumn;
        if (boundColumn != null && boundColumn.Binding is Binding)
        {
            string bindingPropertyPath = (boundColumn.Binding as Binding).Path.Path;
            column.CellStyle = new Style()
            {
                BasedOn = column.CellStyle,
                TargetType = typeof(DataGridCell),
                Triggers =
                {
                    new DataTrigger
                    {
                        Binding = new Binding(bindingPropertyPath) { Converter = new IsNumericConverter() },
                        Value = true,
                        Setters =
                        {
                            new Setter
                            {
                                Property = TextBlock.TextAlignmentProperty,
                                Value = TextAlignment.Right
                            }
                        }
                    }
                }
            };
        }
    }

This method should be safe to call after InitializeComponent() in the code-behind's constructor.

This approach will work if the column has a mixture of numeric and non-numeric data. If the columns contain data of one type only, then this approach will still work, but the triggers created will either never fire or stay fired permanently.

Of course, the above method doesn't have to be repeated in the code-behind for each control that uses DataGrids. You could move it to a static utility class and have all your code-behind classes call this method. You could even add a static utility method that loops through the columns in a DataGrid you pass it and calls the above method for each column.

UPDATE: I modified the above method to allow it deduce the binding property-path. That makes it easier to use. I've also made the method public and static so that it's clear it can be moved to a static utility class.

I did think of another approach, that would run through all of the columns in a DataGrid, inspect the bindings, deduce the type of property bound to and apply the right-alignment to the column. This would avoid creating triggers that never fire or stay permanently fired, and would perhaps fit the case where each column contains data of one type only a bit better. However, this approach would still involve code-behind, it would need to be passed the type that each row would be bound to, and would get complicated if the binding property-paths involved anything more than a single property name.

I'm afraid I can't see a solution to this problem that uses only Styles and avoids code-behind.

2
votes

I know this is three years old, but I was able to get this done without adding any code to the codebehind and I figured I would share how. using this article as a model: link

It uses multibinding as a way of around your original problem of passing a row to your converter.

add this to your datagrid:

CellStyle="{StaticResource CellRightAlignStyle }"

then add this style to your xaml, you must add it as a resource:

<Window.Resources>

    <Style x:Key="CellRightAlignStyle" TargetType="{x:Type DataGridCell}">
        <Setter Property="HorizontalAlignment">
            <Setter.Value>
                <MultiBinding
                    Converter="{converters:IsNumericConverter}" >
                    <MultiBinding.Bindings>
                        <Binding RelativeSource="{RelativeSource Self}"/>
                        <Binding Path="Row" Mode="OneWay"/>
                    </MultiBinding.Bindings>
                </MultiBinding>
            </Setter.Value>
        </Setter>
    </Style>

</Window.Resources>

Then the converter:

    public object Convert(
        object[] values,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
    if (values[1] is DataRow)
        {
            //change the text alignment left or right.
            var cell = (DataGridCell)values[0];
            var row = (DataRow)values[1];
            var columnName = cell.Column.SortMemberPath;

            if (row[columnName] is int || (row[columnName] is decimal ||   row[columnName] is double))
            return System.Windows.HorizontalAlignment.Right;
        }
    return System.Windows.HorizontalAlignment.Left;
    }

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

that is all now your cells that contain numeric data should be right aligned!

0
votes

I use converter for creating a fixed-length string and monospaced font for view.

Converter:

public class AlignRightConverter : IValueConverter // samples: _10 F2_14 C2_16
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            if (parameter == null) throw new Exception("Format is missing");

            var parameterStr = "" + parameter;

            if (!parameterStr.Contains('_')) throw new Exception("Unknown format");

            var parameterParts = parameterStr.Split('_');

            var format = parameterParts[0];

            var lengthStr = parameterParts[1];

            var length = int.TryParse(lengthStr, out int l) ? l : 12;

            if (value == null) return new String(' ', length);

            var type = value.GetType();

            String targetStr;

            if (type == typeof(Double) && format.Length > 0) targetStr = ((Double)value).ToString(format, CultureInfo.GetCultureInfo("ru-ru"));
            else
            if (type == typeof(Single) && format.Length > 0) targetStr = ((Single)value).ToString(format, CultureInfo.GetCultureInfo("ru-ru"));
            else
            if (type == typeof(Int32) && format.Length > 0) targetStr = ((Int32)value).ToString(format, CultureInfo.GetCultureInfo("ru-ru"));
            else
                targetStr = value.ToString();

            if (targetStr.Length >= length) return targetStr;
            else
                return new String(' ', length - targetStr.Length) + targetStr;
        }
        catch (Exception exception)
        {
            exception.Log($"Failed convert to string value {value} with parameters {parameter}");

            return "" + value;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

View:

<DataGridTextColumn Header="Цена покупки" Binding="{Binding Data.CostBuy.Value, Converter={StaticResource AlignRightConverter}, ConverterParameter=C2_16}"  FontFamily="Courier New"  />

Result:

Result