You need to enable JavaScript to run this app. WPF Caliburn.Micro下FluentValidation INotifyDataErrorInfo不触发UI错误提示问题
优惠活动
大模型
产品
解决方案
定价
更多

WPF Caliburn.Micro下FluentValidation INotifyDataErrorInfo不触发UI错误提示问题

问题原因
  • 错误归属对象不匹配:你当前在HomeViewModel的ValidateData方法中调用的是继承自ValidatedPropertyChangedBase的SetError方法,也就是把错误信息存在了ViewModel本身的错误字典里,但XAML绑定路径是Model.FirstName/Model.LastName,WPF的INotifyDataErrorInfo机制是去**绑定源对象(即TestModel实例)**上查错误信息,自然读不到ViewModel里存的错误,也不会触发UI更新。
  • 代码逻辑错误:
    1. TestModelValidation中LastName的校验规则写错了,错误绑定到了FirstName属性
    2. XAML中LastName对应的SfTextBoxExt绑定路径错误写为了Model.FirstName,和FirstName字段重复绑定
    3. ValidatedPropertyChangedBase的SetError方法逻辑缺失:如果对应属性已经存在错误,新的错误不会被追加到错误列表中,只有首次设置错误会生效
  • 校验状态未同步:当前校验结果的有效性只在ValidateData方法内判断,没有对外暴露可绑定的属性通知UI。
解决方案

1. 修正ValidatedPropertyChangedBase代码

先补全SetError逻辑,同时将错误清理方法改为public方便外部调用:

public abstract class ValidatedPropertyChangedBase : PropertyChangedBase, INotifyDataErrorInfo
{
    private readonly Dictionary<string, List<string>> _errors = new Dictionary<string, List<string>>();
    public void SetError(string propertyName, string errorMessage)
    {
        if (!_errors.ContainsKey(propertyName))
            _errors.Add(propertyName, new List<string>());
        // 避免重复添加相同错误
        if(!_errors[propertyName].Contains(errorMessage))
            _errors[propertyName].Add(errorMessage);
        RaiseErrorsChanged(propertyName);
    }
    // 改为public
    public void ClearError(string propertyName)
    {
        if (_errors.ContainsKey(propertyName))
            _errors.Remove(propertyName);
        RaiseErrorsChanged(propertyName);
    }
    // 改为public
    public void ClearAllErrors()
    {
        var errors = _errors.Select(error => error.Key).ToList();
        foreach (var propertyName in errors)
            ClearError(propertyName);
    }
    public void RaiseErrorsChanged(string propertyName)
    {
        ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
    }
    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged = delegate { return; };
    public bool HasErrors
    {
        get { return _errors.Any(x => x.Value != null && x.Value.Count > 0); }
    }
    public IEnumerable GetErrors(string propertyName)
    {
        if (String.IsNullOrEmpty(propertyName) ||
           !_errors.ContainsKey(propertyName)) return null;
        return _errors[propertyName];
    }
}

2. 修正TestModelValidation校验规则

public class TestModelValidation:AbstractValidator<TestModel>
{
    public TestModelValidation()
    {
        RuleFor(t => t.FirstName)
            .NotEmpty()
            .WithMessage("请输入名字");
        // 修正为LastName的校验规则
        RuleFor(t => t.LastName)
            .NotEmpty()
            .WithMessage("请输入姓氏");
    }
}

3. 修正HomeViewModel逻辑,暴露校验状态

public class HomeViewModel : ValidatedPropertyChangedBase
{
    private TestModel _model;
    public TestModel Model
    {
        get { return _model; }
        set
        {
            if (_model != value)
            {
                _model = value;
                NotifyOfPropertyChange(() => Model);
                // 监听Model的错误变化,同步全局状态
                if(_model != null)
                {
                    _model.ErrorsChanged += (s, e) => 
                    {
                        HasGlobalError = _model.HasErrors;
                    };
                }
            }
        }
    }

    // 暴露全局校验状态给视图绑定
    private bool _hasGlobalError;
    public bool HasGlobalError
    {
        get => _hasGlobalError;
        set 
        { 
            _hasGlobalError = value;
            NotifyOfPropertyChange(() => HasGlobalError);
        }
    }

    public HomeViewModel()
    {
        Model = new TestModel();
    }

    public void ValidateData()
    {
        // 清空Model的错误,不是ViewModel的
        Model.ClearAllErrors();
        var validator = new TestModelValidation();
        FluentValidation.Results.ValidationResult result = validator.Validate(Model);
        foreach (var error in result.Errors)
        {
            // 错误设置到Model实例上
            Model.SetError(error.PropertyName, error.ErrorMessage);
        }
        HasGlobalError = !result.IsValid;
        if (result.IsValid)
        {
            MessageBox.Show("数据校验通过,可保存!");
        }
    }
}

4. 修正HomeView.xaml绑定错误

<!-- 修正LastName对应的SfTextBoxExt绑定路径 -->
<sf:SfTextInputLayout
    Hint="Last Name">
    <sf:SfTextBoxExt
        Text="{Binding Path=Model.LastName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" />
</sf:SfTextInputLayout>
<!-- 修正下方标准TextBox的LastName绑定 -->
<TextBox
        Text="{Binding Path=Model.LastName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" />

Syncfusion的SfTextInputLayout默认已支持INotifyDataErrorInfo,只要绑定源对象正确实现接口,错误信息会自动展示,无需额外修改控件代码。

内容的提问来源于stack exchange,提问作者Infii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 07:54:07