Home > database >  WPF xaml: How to validate Cells in DataGrid with automatically generated Columns
WPF xaml: How to validate Cells in DataGrid with automatically generated Columns

Time:11-22

How can I add cell validation in an automatically generated DataGrid (from DataTable) and style the cell red if the value is not valid?

This is my DataGrid:

    <DataGrid Grid.Row="2"
              Margin="5"
              Background="Transparent"
              MaxHeight="300"
              MaxWidth="500"
              ScrollViewer.CanContentScroll="True"
              HorizontalAlignment="Center"
              VerticalAlignment="Center"
              ItemsSource="{Binding DataTable}"
              HeadersVisibility="None"
              CellStyle="{StaticResource tableCellTheme}"
              CanUserAddRows="False">

I also added

        <DataGrid.RowValidationRules>
            <validation:DataGridValidation ValidationStep="UpdatedValue" />
        </DataGrid.RowValidationRules>

But I do not want to evaluate the whole row and more importantly, I don't know how to style the offending cell red if this returns false... Thanks for your help!

CodePudding user response:

You must handle the DataGrid.AutoGeneratingColumn event, obtain the reference to the column's binding and then enable binding validation and attach the ValidationRule to it:

MainWindow.xaml

<DataGrid AutoGeneratingColumn="EnableCellValidation_OnAutoGeneratingColumn" />

MainWindow.xaml.cs

private void EnableCellValidation_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
  if (e.Column is DataGridBoundColumn column)
  {
    var columnBinding = column.Binding as Binding;
    columnBinding.ValidatesOnDataErrors = true;
    columnBinding.ValidationRules.Add(new DataGridValidation());
  }
}
  • Related