DataGridTemplateColumn and validation

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

Hello!

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">
    <Controls:DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
        <TextBlock Text="{Binding Warehouse, ValidatesOnDataErrors=True}">
        </TextBlock>
      </DataTemplate>
    </Controls:DataGridTemplateColumn.CellTemplate>
    <Controls:DataGridTemplateColumn.CellEditingTemplate>
      <DataTemplate>
        <ComboBox SelectedItem="{Binding Warehouse, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
          ItemsSource="{Binding Warehouses}">
        </ComboBox>
      </DataTemplate>
    </Controls:DataGridTemplateColumn.CellEditingTemplate>
  </Controls:DataGridTemplateColumn>

</Controls:DataGrid>

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? 

Thanks!

May 31, 2011 at 7: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.

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

The add the style...

 <Style x:Key="CellViewStyle" TargetType="{x:Type Label}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">    
                    <Setter Property="ToolTip"
                            Value="{Binding RelativeSource={RelativeSource Self},
                                    Path=(Validation.Errors)[0].ErrorContent}"/>
                    <Setter Property="BorderBrush" Value="Red" />
                    <Setter Property="BorderThickness" Value="1" />
                 </Trigger>
            </Style.Triggers>
        </Style>

Jun 2, 2011 at 4:41 AM

Works like a charm. Thanks a lot!