在后面的代码中为每个表添加一个部分类。
如果没有错误,属性 [HasNoError] 返回 true
属性 [Error] 以字符串形式返回错误
if(tablename.HasNoError)
{
// do your logic
}
else
{
// display tablename.Error
}
在xaml端使用绑定
<DataGridTextColumn Binding="{Binding Path=ActualFieldName1, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged }" Header=" ActualFieldName1" />
这是使用 IDataErrorInfo 的类示例-
public partial class tablename : IDataErrorInfo
{
private Dictionary<string, string> errorCollection = new Dictionary<string, string>();
public bool HasNoError
{
get
{
return string.IsNullOrWhiteSpace(Error);
}
}
public string Error
{
get
{
if (errorCollection.Count == 0)
return null;
StringBuilder errorList = new StringBuilder();
var errorMessages = errorCollection.Values.GetEnumerator();
while (errorMessages.MoveNext())
errorList.AppendLine(errorMessages.Current);
return errorList.ToString();
}
}
public string this[string fieldName]
{
get
{
string result = null;
switch (fieldName)
{
case "ActualFieldName1":
if (string.IsNullOrWhiteSpace(this.ActualFieldName1))
{
result = "ActualFieldName1 is required.";
};
if (Other_Condition)
{
result = "Other Result";
};
break;
case "ActualFieldName2":
if (string.IsNullOrWhiteSpace(this.ActualFieldName2))
{
result = "ActualFieldName2 is required.";
};
if (Other_Condition)
{
result = "Other Result";
};
break;
// and so
}
if (result != null && !errorCollection.ContainsKey(fieldName))
errorCollection.Add(fieldName, result);
if (result == null && errorCollection.ContainsKey(fieldName))
errorCollection.Remove(fieldName);
return result;
}
}
}
为了更好地添加一些样式以定位错误模板,请参阅示例
<Style TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<Border BorderBrush="Red" BorderThickness="1">
<Grid>
<AdornedElementPlaceholder x:Name="MyAdorner"/>
<Image Width="{Binding AdornedElement.ActualHeight, ElementName=MyAdorner}" Margin="0" ToolTip="{Binding AdornedElement.(Validation.Errors)[0].ErrorContent, ElementName=MyAdorner}" HorizontalAlignment="Right" VerticalAlignment="Center" Source="/Path/Exclamation.png" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>