I am using a DataGrid for showing and editing data. The view (datagrid) is bound to a viewmodel. No I added a custom ValidationRule (following this tutorial: http://blogs.u2u.be/diederik/post/2009/09/30/Validation-in-a-WPF-DataGrid.aspx)
namespace Presentation.ViewsRoot.ValidationRules
{
class IsPositiveIntegerRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if (string.IsNullOrEmpty(value as string))
{
return new ValidationResult(true, null);
}
else
{
int proposedValue;
if (!int.TryParse(value.ToString(), out proposedValue))
{
return new ValidationResult(false, "'" + value.ToString() + "' ist no positive integer (>=0).");
}
if (proposedValue < 0)
{
// Something was wrong.
return new ValidationResult(false, "Value can't be smaller than 0.");
}
}
// Everything OK.
return new ValidationResult(true, null);
}
}
}
I am binding to this validationrule in xaml
<DataGridTextColumn Header="Shitfs" IsReadOnly="False">
<DataGridTextColumn.Binding>
<Binding Path="Shifts">
<Binding.ValidationRules>
<validationRules:IsPositiveIntegerRule />
</Binding.ValidationRules>
</Binding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
The cell gets a red border when entering wrong values and the rowheader shows a red exclamation mark (!). But no Tooltip with message is shown. I tried adding a custom style in UserControl.Resources but it didn't work:
<Style TargetType="TextBlock">
<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>
Any ideas on how to show the errorcontent in a tooltip in a datagrid? I think I am missing something essential, but I can't find what...
Working Solution:
<Style x:Key="CellEditStyle" TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
Combining the comments about using {Binding RelativeSource Self} and referencing it by name works. I also had to change TargetType from TextBlock to TextBox. Thanks for the helpful comments.
<Setter Property="ToolTip" Value="RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>-> no tooltip :( - basti