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.
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?
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With