我有一个ValidationRule,我想将其用于验证DataGrid中的用户输入。
可能是因为用户输入的数据违反了一个以上的规则,因此可以在IDataErrorInfo
实现类中检测到某些规则破坏者,而在ValidationRule
类中可以检测到某些破坏者。因此,我想针对特定单元格将所有这些错误消息组合并显示给用户(也许使用工具提示) 。
例如,我要检查是否为';'包含在任何单元格中。我想在ValidationRule
类中进行检查。
特定于某个单元的检查应在IDataErrorInfo
实现模型类中完成。
我该如何实现?
我的IDataErrorInfo实现类:
public class RawTag : IDataErrorInfo, INotifyPropertyChanged
{
private int hash;
private string tagName;
private string cycle;
private string source;
public RawTag()
{
RefreshHash();
}
public void RefreshHash()
{
hash = GetHashCode();
}
public RawTag(string tagName, string cycle, string source)
{
TagName = tagName;
Cycle = cycle;
Source = source;
RefreshHash();
}
public string TagName
{
get => tagName;
set
{
if (value == tagName) return;
tagName = value;
OnPropertyChanged();
}
}
// should be an integer but any entered value shall be accepted
public string Cycle
{
get => cycle;
set
{
if (value == cycle)
{
return;
}
cycle = value;
OnPropertyChanged();
}
}
public string Source
{
get => source;
set
{
if (value == source) return;
source = value;
OnPropertyChanged();
}
}
string IDataErrorInfo.Error
{
get
{
StringBuilder error = new StringBuilder();
if (string.IsNullOrEmpty(TagName))
{
error.Append("Name cannot be null or empty");
}
if (!int.TryParse(Cycle.ToString(), out int i))
{
error.Append("Cycle should be an integer value.");
}
return error.ToString();
}
}
private void checkIfEmptyfieldsExists()
{
PropertyInfo[] properties = this.GetType().GetProperties();
}
private bool checkForInvalidCharacter(string value, string character)
{
return value.Contains(character);
}
string IDataErrorInfo.this[string columnName]
{
get
{
// apply property level validation rules
if (columnName == "TagName")
{
if (string.IsNullOrEmpty(TagName))
return "Name cannot be null or empty";
}
if (columnName == "Cycle")
{
if (!int.TryParse(Cycle.ToString(), out int i))
return "Cycle should be an integer value.";
}
if (columnName == "Source")
{
if (string.IsNullOrEmpty(Source))
return "Source must not be empty";
}
return "";
}
}
public override string ToString()
{
return "TagName: " + TagName + " Cycle: " + Cycle + " Source: " + Source;
}
public bool IsDirty()
{
return hash != GetHashCode();
}
protected bool Equals(RawTag other)
{
return string.Equals(TagName, other.TagName) && string.Equals(Cycle, other.Cycle) && string.Equals(Source, other.Source);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((RawTag)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (TagName != null ? TagName.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Cycle != null ? Cycle.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Source != null ? Source.GetHashCode() : 0);
return hashCode;
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
我的ValidationRule类:
public class MyValidationRule : ValidationRule
{
public override ValidationResult Validate(object value,
System.Globalization.CultureInfo cultureInfo)
{
BindingGroup group = (BindingGroup)value;
StringBuilder error = null;
foreach (var item in group.Items)
{
IDataErrorInfo info = item as IDataErrorInfo;
if (info != null)
{
if (!string.IsNullOrEmpty(info.Error))
{
if (error == null)
{
error = new StringBuilder();
}
Type type = item.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine(property.GetValue(property.Name, null));
if (property.GetValue(property.Name, null).ToString().Contains(";"))
{
error.Append((error.Length != 0 ? ", " : "") + property.Name + " may not contain a ';'.");
}
}
error.Append((error.Length != 0 ? ", " : "") + info.Error);
}
}
}
if (error != null)
return new ValidationResult(false, error.ToString());
else
return new ValidationResult(true, "");
}
}
通过这种方式,LOC在CycleValidationRule中:if (error != null)
return new ValidationResult(false, error.ToString());
显示所有收集到的错误消息,但是当悬停单元格时,在DataGrid的最终工具提示中只有
“周期应为整数值。”
似乎已定义样式:
<Style x:Key="textBlockErrStyle" TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=(Validation.HasError), RelativeSource={RelativeSource AncestorType=DataGridRow}}" Value="true" >
<Setter Property="Background" Value="Red" />
<Setter Property="Foreground" Value="White" />
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
</DataTrigger>
</Style.Triggers>
</Style>
绑定到IDataErrorInfo
,但没有绑定到我的CycleValiadtionRule
验证错误。