Does anyone have any example on Cross row validation for WPF Datagrid. Cell level validation and Rowlevel validation doesn't fulfill my requirements. i am trying to stick with MVVM as much as possible. my last option is to use code behind. so basically i need to access the Itemssource when something happens in the grid. any help is much appreciated. Thanks -Rey
1 Answers
1
votes
on the code behind add a partial class to each table.
The property [HasNoError] is return true if there are no errors
The property [Error] is return the errors as string
if(tablename.HasNoError)
{
// do your logic
}
else
{
// display tablename.Error
}
In the xaml side use the binding
<DataGridTextColumn Binding="{Binding Path=ActualFieldName1, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged }" Header=" ActualFieldName1" />
and this is the class sample using 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;
}
}
}
To make it nice add some style to target the error template see the example
<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>