I have been researching this topic for hours and can't find a solution that works for me.
I have a simple WPF program that uses a datagrid to display a list of objects from the code (in very much the same way as the msdn demo)
My data is taken from a SQL database and placed into a list of objects which is bound to the datagrid as below:
public PersonInfo()
{
InitialiseComponent();
LoadPeopleFromSQL();
}
public void LoadPeopleFromSQL()
{
DataSet ds = GetDataSet(SQLConnectionString);
List<PersonInfo> personList = new List<PersonInfo>();
foreach(DataRow row in ds.Tables[0].Rows)
{
personList.Add(new PersonInfo(row[0], row[1], row[2]));
}
PersonDataGrid.ItemsSource = personList;
I have set up a ValidationRule class containing a public override ValidationResult Validate() method that exactly matches the structure msdn example: http://msdn.microsoft.com/en-us/library/system.windows.controls.datagrid.rowvalidationrules%28v=vs.110%29.aspx (except that it uses my 'Person' object rather than a 'Course' object)
public class CourseValidationRule : ValidationRule
{
public override ValidationResult Validate(object value,
System.Globalization.CultureInfo cultureInfo)
{
Course course = (value as BindingGroup).Items[0] as Course;
if (course.StartDate > course.EndDate)
{
return new ValidationResult(false,
"Start Date must be earlier than End Date.");
}
else
{
return ValidationResult.ValidResult;
}
}
}
//Xaml snippet
<DataGrid.RowValidationRules>
<local:CourseValidationRule ValidationStep="UpdatedValue"/>
</DataGrid.RowValidationRules>
However, what I would like to do now is search through the rest of the items in the datagrid and check to make sure the PersonInfo.ID field has not been duplicated. I found this code:http://www.codeproject.com/Articles/30905/WPF-DataGrid-Practical-Examples#valid_dataset
But this example expects the BindingGroup object to return a datarow, not a class object.
I noticed that the BindingGroup object has a property called 'Owner' which appears to contain a datarow. However I am using .net 4 and can't access the 'Owner' property.
Please can someone show me how to validate my primary key? Or help me access the BindingGroup.Owner property from within .net 4 (which I believe would fix my issue)
The issue here was transferring my full list of 'People' from my main working class to the DataRowValidation class.
As I could not find a way to bind to the DataRow object, I placed a public property inside the DataRowValidation class and filled it with the current list of people from my main class:
public class DataRowValidation : ValidationRule
{
public List<PersonInfo> People {get; set;}
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if (value is BindingGroup)
{
BindingGroup group = (BindingGroup)value;
People = PersonClass.personList;
//Code to loop through list and test for duplicates
}
}
}