Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display validation error in DataGridCell tooltip

Tags:

wpf

datagrid

I have a WPF DataGrid which displays types that implement IDataErrorInfo. As expected when the validation fails the row gets the red exclamation mark and the invalid cell gets the red highlight. enter image description here

This is all well and good; however, I want the validation error message to display in the tooltip of the invalid cell so the user has some indication of what is wrong. I presently have:

<DataGrid.CellStyle>
    <Style TargetType="DataGridCell">
        <Setter Property="ToolTip"
                Value="{Binding RelativeSource={RelativeSource Self},
                                                Path=(Validation.Errors[0].ErrorContent}"/>
     </Style>
</DataGrid.CellStyle>

This approach works for TextBox but not for DataGridCell. What is the difference?

like image 873
Brian Triplett Avatar asked Sep 21 '11 17:09

Brian Triplett


2 Answers

I have something similiar in a project I'm working on right now, and it goes something like this:

<DataGridTextColumn.ElementStyle>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="DataGridCell.ToolTip"
                Value="{Binding RelativeSource={RelativeSource Self},
                                                Path=(Validation.Errors)[0].ErrorContent}"/>
     </Style>
</DataGridTextColumn.ElementStyle>
like image 83
Jelle Capenberghs Avatar answered Nov 16 '22 19:11

Jelle Capenberghs


Take a look at this MSDN log post:

https://blogs.msdn.microsoft.com/bethmassi/2008/06/27/displaying-data-validation-messages-in-wpf/

Follow its instructions to create a textbox cell editing template that will look something like this:

<Style TargetType="TextBox" x:Key="errTemplate">
  <Style.Triggers>
    <Trigger Property="Validation.HasError" Value="true">
      <Setter Property="ToolTip"
              Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                     Path=(Validation.Errors)[0].ErrorContent}"/>
    </Trigger>
  </Style.Triggers>
</Style>

Then, you can use it in your datagrid by setting the EditingElementStyle like so:

<DataGridTextColumn Header="Variable" 
                    Binding="{Binding Variable, ValidatesOnDataErrors=True}" 
                    EditingElementStyle="{StaticResource errTemplate}"/>

It is important to use the data trigger so that you can support a standard tool tip as well as a tool tip when there is an error as explained in this post:

Tooltip Not Showing Up When No Validation Error WPF

like image 40
Eric Avatar answered Nov 16 '22 19:11

Eric