2025-02-10 20:53:40 +08:00
|
|
|
|
using System.Windows;
|
2024-09-22 11:05:41 +08:00
|
|
|
|
using System.Windows.Controls;
|
2025-02-10 20:53:40 +08:00
|
|
|
|
using Microsoft.Xaml.Behaviors;
|
2024-09-22 11:05:41 +08:00
|
|
|
|
|
2025-02-10 20:53:40 +08:00
|
|
|
|
namespace ShrlAlgo.Toolkit.Mvvm.Behaviors;
|
2024-09-22 11:05:41 +08:00
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 在xaml的资源中声明,viewModel继承IValidationExceptionHandler,通过IsValid判断能否执行
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public class ValidationRuleBehavior : Behavior<FrameworkElement>
|
|
|
|
|
|
{
|
|
|
|
|
|
private int errorCount;
|
|
|
|
|
|
|
|
|
|
|
|
protected override void OnAttached()
|
|
|
|
|
|
{
|
|
|
|
|
|
base.OnAttached();
|
|
|
|
|
|
AssociatedObject.AddHandler(Validation.ErrorEvent, new EventHandler<ValidationErrorEventArgs>(OnValidationError));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
protected override void OnDetaching()
|
|
|
|
|
|
{
|
|
|
|
|
|
AssociatedObject.RemoveHandler(Validation.ErrorEvent, new EventHandler<ValidationErrorEventArgs>(OnValidationError));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private void OnValidationError(object sender, ValidationErrorEventArgs e)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (AssociatedObject.DataContext is IValidationExceptionHandler handler)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (e.OriginalSource is UIElement elem)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (e.Action == ValidationErrorEventAction.Added)
|
|
|
|
|
|
{
|
|
|
|
|
|
errorCount++;
|
|
|
|
|
|
}
|
|
|
|
|
|
else if (e.Action == ValidationErrorEventAction.Removed)
|
|
|
|
|
|
{
|
|
|
|
|
|
errorCount--;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
handler.IsValid = errorCount == 0;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|