我正在使用DataGrid来显示和编辑数据。视图(datagrid)绑定到viewmodel。不,我添加了自定义ValidationRule(遵循本教程: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);
}
}
}
我在xaml
中绑定了这个validationrule<DataGridTextColumn Header="Shitfs" IsReadOnly="False">
<DataGridTextColumn.Binding>
<Binding Path="Shifts">
<Binding.ValidationRules>
<validationRules:IsPositiveIntegerRule />
</Binding.ValidationRules>
</Binding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
输入错误值时,单元格会出现红色边框,并且行标题会显示红色感叹号(!)。但是没有显示带有消息的工具提示。我尝试在UserControl.Resources
中添加自定义样式,但它不起作用:
<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>
有关如何在数据网格中的工具提示中显示错误内容的任何想法?我想我错过了必不可少的东西,但我找不到什么...
工作解决方案:
<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>
结合使用{Binding RelativeSource Self}
的注释并按名称引用它的作用。我还必须将TargetType从TextBlock
更改为TextBox
。感谢您提供的有用评论。
答案 0 :(得分:0)
尝试
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>