gpt4 book ai didi

c# - 如何确定 Validation.ErrorEvent 中是否不再有错误?

转载 作者:行者123 更新时间:2023-11-30 17:25:29 25 4
gpt4 key购买 nike

我非常简单地检查我的窗口中是否存在验证错误(假设所有绑定(bind)都设置了 NotifyOnValidationError):

public MainWindow()
{
InitializeComponent();
DataContext = new VM();
AddHandler(Validation.ErrorEvent, new RoutedEventHandler((s, e) =>
{
var args = (ValidationErrorEventArgs)e;
var binding = (BindingExpression)args.Error.BindingInError;
Title = binding.HasError ? $"Error {args.Error.ErrorContent}" : "";
}), true);
}

当错误出现/消失时触发事件,但由于某些原因 HasError 仍然是 true 当没有更多错误并且 ErrorContent 包含旧错误文本。

我做错了什么?


下面是一个简单的 MCVE,验证 Test 应该是 0

绑定(bind)错误(输入 0a 或空字符串)已正确设置/重置。验证错误设置正确(输入 1 时),但未重置(输入 0 时)。为什么?

实现 INotifyPropertyChange 没有任何区别。

xaml:

<TextBox Text="{Binding Test, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged}" />

查看模型:

public class VM : INotifyDataErrorInfo
{
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

int _test;
public int Test
{
get => _test;
set
{
_test = value;
_error = value == 0 ? null : "Must be 0";
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Test)));
}
}

string _error;
public bool HasErrors => _error != null;

public IEnumerable GetErrors(string propertyName)
{
if (_error != null)
yield return _error;
}

}

最佳答案

如果您从处理程序中设置 Title,我认为您需要考虑 ValidationErrorEventArgs.Action属性:

Gets a value that indicates whether the error is a new error or an existing error that has now been cleared.

我不是 100% 确定,但我怀疑当您检查 HasError 属性时,它还没有被清除。 (基于的怀疑“另请注意,任一方向(目标到源或源到目标)的有效值传输都会清除 Validation.Errorsattached 属性。” 来自 MSDN )

关于c# - 如何确定 Validation.ErrorEvent 中是否不再有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58539590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com