DataGridTemplateColumn and validation

May 30, 2011 at 3:50 AM
Edited May 30, 2011 at 3:52 AM


I'm wondering if it is possible to force displaying validation red rectangle around cell which column is DataGridTemplateColumn. My situation is the following: I have a datagrid and a couple of columns. One of these columns is template column and others are text columns. I databind datagrid to the Items property from my viewmodel (I'm using MVVM pattern, viewmodel implements IDataErrorInfo and INotifyPropertyChanged interfaces). XAML for template column is like the following:


<Controls:DataGrid ItemsSource="{Binding Items}">

  <Controls:DataGridTemplateColumn Header="Warehouse">
        <TextBlock Text="{Binding Warehouse, ValidatesOnDataErrors=True}">
        <ComboBox SelectedItem="{Binding Warehouse, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
          ItemsSource="{Binding Warehouses}">


Warehouse is required field and I want to display generic red border over this cell when warehouse isn't chosen. However, the red border is only visible when row in edit mode and it is shown over the combobox. In view mode there is no any suggestion about what cell is invalid.

Has anyone faced such a problem? Is there any way to display red border over cell itself? 


May 31, 2011 at 6:08 PM

The easiest way is to change the the DataTemplate TextBlock to a label (TextBlock doesn't have a border.) and then apply a conditional style to it.

        <Label Content="{Binding Warehouse, ValidatesOnDataErrors=True}" Style="{StaticResource CellViewStyle}">

The add the style...

 <Style x:Key="CellViewStyle" TargetType="{x:Type Label}">
                <Trigger Property="Validation.HasError" Value="true">    
                    <Setter Property="ToolTip"
                            Value="{Binding RelativeSource={RelativeSource Self},
                    <Setter Property="BorderBrush" Value="Red" />
                    <Setter Property="BorderThickness" Value="1" />

Jun 2, 2011 at 3:41 AM

Works like a charm. Thanks a lot!