Files
ShrlAlgoToolkit/ShrlAlgoToolkit.Mvvm/Behaviors/ValidationRuleBehavior.cs
2025-04-24 20:56:44 +08:00

45 lines
1.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Windows;
using System.Windows.Controls;
using Microsoft.Xaml.Behaviors;
namespace ShrlAlgoToolkit.Mvvm.Behaviors;
/// <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;
}
}
}