有没有人对WPF Datagrid的跨行验证有任何示例。单元级别验证和行级验证不符合我的要求。我想尽可能地坚持使用MVVM。我的最后一个选择是使用代码。所以基本上我需要在网格中发生某些事情时访问Itemssource。任何帮助深表感谢。 谢谢-Rey
答案 0 :(得分:1)
在后面的代码中为每个表添加一个分部类。
如果没有错误,属性[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>