Latest DataGrid, Custom Validation Styling

Nov 21, 2008 at 5:16 PM
Hi There,

I am using the new Data Grid from latest release (Oct 2008). I am not achieving correct validation styling.

I want to turn a data cell belonging to Name column into green when errors occur (e.g. empty value is provided) ... The data context of the grid is an observable collection of Employee class that has a single attribute "Name"

Following is the Data Grid XAML...

<my:DataGrid Name="DataGrid1" ItemsSource="{Binding}" AutoGenerateColumns="False" VerticalAlignment="Top">

   <Style x:Key="MyGridCell" TargetType="{x:Type my:DataGridCell}">
       <Trigger Property="Validation.HasError" Value="True">
         <Setter Property="Background" Value="Green"/>

   <my:DataGridTextColumn Header="Name" CellStyle="{StaticResource MyGridCell}">
         <Binding Path="Name" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True">


Following is the Employee Class...

Class Employee   
    Implements System.ComponentModel.INotifyPropertyChanged, IDataErrorInfo

    Private _name As String

    Public Property Name() As String
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
            RaiseEvent PropertyChanged(Me, New System.ComponentModel.PropertyChangedEventArgs("Name"))
        End Set
    End Property

    Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged

    Default Public Overloads ReadOnly Property Item(ByVal columnName As String) As String Implements System.ComponentModel.IDataErrorInfo.Item
            Dim result As String = String.Empty
            If (columnName = "Name") Then
                If String.IsNullOrEmpty(Me.Name) Then
                    result = "Name cannot be blank!"
                End If
            End If
            Return result
        End Get
    End Property

    Public ReadOnly Property [Error]() As String Implements System.ComponentModel.IDataErrorInfo.Error
            Return Me(String.Empty)
        End Get
    End Property
End Class



Dec 5, 2008 at 1:53 PM
Take a look at the sample on this post,  It shows how cell and item level validation can be achieved.  For your scenario you will want to set the background to green on the TextBox and not the DataGridCell.  There are a couple known issues too to be aware about.  You can read more on that here,