using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Perspex.Data;
namespace Perspex.Markup.Data.Plugins
{
///
/// Validates properties that report errors by throwing exceptions.
///
public class ExceptionValidationCheckerPlugin : IValidationCheckerPlugin
{
///
public bool Match(WeakReference reference) => true;
///
public ValidationCheckerBase Start(WeakReference reference, string name, IPropertyAccessor accessor, Action callback)
{
return new ExceptionValidationChecker(reference, name, accessor, callback);
}
private class ExceptionValidationChecker : ValidationCheckerBase
{
public ExceptionValidationChecker(WeakReference reference, string name, IPropertyAccessor accessor, Action callback)
: base(reference, name, accessor, callback)
{
}
public override bool SetValue(object value, BindingPriority priority)
{
try
{
var success = base.SetValue(value, priority);
SendValidationCallback(new ExceptionValidationStatus(null));
return success;
}
catch (Exception ex)
{
SendValidationCallback(new ExceptionValidationStatus(ex));
}
return false;
}
}
///
/// Describes the current validation status after setting a property value.
///
public class ExceptionValidationStatus : ValidationStatus
{
internal ExceptionValidationStatus(Exception exception)
{
Exception = exception;
}
///
/// The thrown exception. If there was no thrown exception, null.
///
public Exception Exception { get; }
///
public override bool IsValid => Exception == null;
}
}
}