【发布时间】:2012-09-27 12:37:55
【问题描述】:
我正在使用 DataGrid 来显示和编辑数据。视图(数据网格)绑定到视图模型。不,我添加了一个自定义 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 中的这个验证规则
<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} 并通过名称引用它的cmets 是可行的。我还必须将 TargetType 从 TextBlock 更改为 TextBox。感谢 cmets 的帮助。
【问题讨论】:
-
在我的情况下,它确实适用于 RelativeSource={RelativeSource Self}
-
@FlorianGl : 更改为
<Setter Property="ToolTip" Value="RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>-> 没有工具提示 :( -
试试
-
@FlorianGl 如果您发表评论作为答案,我会接受。所以它至少在谷歌等上是可行的。:)
标签: wpf validation datagrid tooltip