In my financial application I have a DataGrid with a DataTable as ItemSource. I'm using the DataTable because of the flexibility to view queries with different number of columns. So, the viewmodel creates the DataTable. The AutoGenerateColumns="True" to support the flexibility. I added some logic in the UI to highlight negative values. The XAML code:
<DataGrid Grid.Row="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding Totals}" AutoGenerateColumns="True" CanUserAddRows="False"> <DataGrid.CellStyle> <Style TargetType="DataGridCell"> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Content.Text, Converter={StaticResource isNullConverter}}" Value="False"> <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=Content.Text, Converter={StaticResource valueToColor}}" /> </DataTrigger> </Style.Triggers> </Style> </DataGrid.CellStyle> </DataGrid>
It uses a ValueConverter to determine if the cell is not empty and to set the Background color based on the value.
public class ValueToColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((value.GetType() == typeof(string))) { if (decimal.TryParse((string)value, out decimal decimalValue)) { if (decimalValue < 0) { return Brushes.Orange as Brush; } else { return Brushes.White as Brush; } } return Brushes.White as Brush; } throw new NotImplementedException($"No conversion from type {value.GetType()} to a Brush"); } }
As a first step works fine with the following result:
However I profer to have a more subtile formatting, by just coloring the Foreground color of the textbox and with right alignment:
I could not find a way to format the TextBox of the cell.
How can you achieve it, preferably in XAML