using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using SchoolSample.EntityModel;
namespace SchoolSample
{
public static class ValidationSummaryBehavior
{
#region "TargetofObjectError"
public static IObjectWithChangeTracker GetTargetofObjectError(ValidationSummary validationSummary)
{
return (IObjectWithChangeTracker) validationSummary.GetValue(TargetofObjectErrorProperty);
}
public static void SetTargetofObjectError(ValidationSummary validationSummary, IObjectWithChangeTracker value)
{
validationSummary.SetValue(TargetofObjectErrorProperty, value);
}
public static readonly DependencyProperty TargetofObjectErrorProperty =
DependencyProperty.RegisterAttached(
"TargetofObjectError",
typeof (IObjectWithChangeTracker),
typeof (ValidationSummaryBehavior),
new UIPropertyMetadata(null, OnTargetofObjectErrorChanged));
private static readonly List<KeyValuePair<IObjectWithChangeTracker, ValidationSummary>> KeyValuePairs =
new List<KeyValuePair<IObjectWithChangeTracker, ValidationSummary>>();
private static void OnTargetofObjectErrorChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
var validationSummary = depObj as ValidationSummary;
if (validationSummary == null) return;
if (e.OldValue is IObjectWithChangeTracker)
{
foreach (var keyValuePair in KeyValuePairs
.Where(item => item.Key.Equals(e.OldValue) && item.Value.Equals(validationSummary))
.ToList())
{
KeyValuePairs.Remove(keyValuePair);
}
if (e.OldValue is INotifyDataErrorInfo)
{
((INotifyDataErrorInfo) e.OldValue).ErrorsChanged -= ValidationSummaryBehavior_ErrorsChanged;
}
}
if (e.NewValue is IObjectWithChangeTracker)
{
KeyValuePairs.Add(
new KeyValuePair<IObjectWithChangeTracker, ValidationSummary>(
(IObjectWithChangeTracker) e.NewValue, validationSummary));
if (e.NewValue is INotifyDataErrorInfo)
{
((INotifyDataErrorInfo) e.NewValue).ErrorsChanged += ValidationSummaryBehavior_ErrorsChanged;
}
}
}
private static void ValidationSummaryBehavior_ErrorsChanged(object sender, DataErrorsChangedEventArgs e)
{
var item = sender as IObjectWithChangeTracker;
if (item != null)
{
foreach (ValidationSummary validationSummary in KeyValuePairs
.Where(n => n.Key.Equals(item)).Select(n => n.Value))
{
// remove all existing ObjectError
foreach (var validationSummaryItem in validationSummary.Errors
.Where(n => n.ItemType == ValidationSummaryItemType.ObjectError).
ToList())
{
validationSummary.Errors.Remove(validationSummaryItem);
}
// update ObjectError
var iNotifyDataErrorInfo = item as INotifyDataErrorInfo;
if (iNotifyDataErrorInfo != null && iNotifyDataErrorInfo.GetErrors(string.Empty) != null)
{
foreach (System.ComponentModel.DataAnnotations.ValidationResult validationResult in
iNotifyDataErrorInfo.GetErrors(string.Empty))
{
validationSummary.Errors.Add(new ValidationSummaryItem(validationResult.ErrorMessage));
}
}
}
}
}
#endregion "TargetofObjectError"
}
}