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...
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 Style
s and avoids code-behind.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With