【问题标题】:Cross property validation using INotifyDataErrorInfo not working使用 INotifyDataErrorInfo 的跨属性验证不起作用
【发布时间】:2020-11-30 22:20:21
【问题描述】:

我正在尝试在我的 MVVM 项目中实现验证,并在 Model 上完成验证。下面是一个最小的例子:

查看:

Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Test"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:VM x:Key="VM"/>
    </Window.Resources>
    <Grid DataContext="{StaticResource VM}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <Label Grid.Row="0" Grid.Column="0" Content="Number: "/>
        <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Number, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
                 ToolTip="{Binding Path=(Validation.Errors)/ErrorContent, RelativeSource={RelativeSource Mode=Self}}"/>
        <Label Grid.Row="1" Grid.Column="0" Content="Limit: "/>
        <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Limit, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
                 ToolTip="{Binding Path=(Validation.Errors)/ErrorContent, RelativeSource={RelativeSource Mode=Self}}"/>
    </Grid>
</Window>

视图模型:

public class ViewModel : INotifyPropertyChanged, INotifyDataErrorInfo
{
    private Model _model = new Model();

    public int Number
    {
        get { return this._model.Number; }
        set
        {
            if (value != this._model.Number)
                this._model.Number = value;
        }
    }

    public int Limit
    {
        get { return this._model.Limit; }
        set
        {
            if (value != this._model.Limit)
                this._model.Limit = value;
        }
    }

    public ViewModel()
    {
        this._model.PropertyChanged += (sender, args) => this.PropertyChanged?.Invoke(sender, args);
        this._model.ErrorsChanged += (sender, args) => this.ErrorsChanged?.Invoke(sender, args);
    }

    public bool HasErrors => this._model.HasErrors;

    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
    public event PropertyChangedEventHandler PropertyChanged;

    public IEnumerable GetErrors(string propertyName) => this._model.GetErrors(propertyName);
}

型号:

public class Model : INotifyPropertyChanged, INotifyDataErrorInfo
{
    private int _number;
    public int Number
    {
        get => _number;
        set
        {
            if (_number != value)
            {
                _number = value;
                OnPropertyChanged();
                //ValidateNumber();
            }
        }
    }

    private int _limit;
    public int Limit
    {
        get => _limit;
        set
        {
            if (_limit != value)
            {
                _limit = value;
                OnPropertyChanged();
                ValidateNumber();
            }
        }
    }

    private void ValidateNumber()
    {
        var propertyName = nameof(Number);
        if (Number > Limit)
            _errors[propertyName] = new[] { "Number cannot be larger than Limit." };
        else
        {
            if (_errors.ContainsKey(propertyName))
                _errors.Remove(propertyName);
        }

        OnErrorChanged(propertyName);
    }

    private Dictionary<string, IEnumerable<string>> _errors = new Dictionary<string, IEnumerable<string>>();

    public bool HasErrors => _errors.Values.Any(err => err != null);

    public event PropertyChangedEventHandler PropertyChanged;
    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

    public IEnumerable GetErrors(string propertyName) => _errors.ContainsKey(propertyName) ? _errors[propertyName] : Enumerable.Empty<object>();

    private void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    private void OnErrorChanged([CallerMemberName] string propertyName = null) => ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}

从示例中,Number 属性应该在 Limit 更改时进行验证,Number 的验证错误应该显示在视图上。但是,可以观察到验证方法已执行,但视图上的 Number 字段未显示验证错误。

从this article 看来,INotifyDataErrorInfo 似乎应该支持这种跨属性验证。

【问题讨论】:

    标签: c# wpf validation mvvm inotifydataerrorinfo


    【解决方案1】:

    绑定引擎似乎希望INotifyDataErrorInfo.ErrorsChanged 事件的sender 与绑定源所在的对象相同。

    变化

    this._model.ErrorsChanged += (sender, args) => this.ErrorsChanged?.Invoke(sender, args);
    

    到

    this._model.ErrorsChanged += (sender, args) => this.ErrorsChanged?.Invoke(this, args);
    

    解决了这个问题。

    有知道为什么要这样设计的专家吗? (我花了一整天的时间来解决这个问题)

    【讨论】:

    • BindingExpression 使用WeakEventManager 实现来监听INotifyDataErrorInfo.ErrorsChanged 事件。这个经理就像一个聚合器。它使用事件源 (ViewModel) 作为查找键注册 BindingExpression 的事件处理程序。然后,经理收听该事件。引发事件时,管理器使用事件源(发送者)查找相应的事件处理程序。由于发送者 (Model) 与最初注册的事件源 (ViewModel) 不同,因此管理器找不到事件处理程序,因此无法传递事件。
    • 所描述的行为是每个WeakEventManager 实现的默认行为。
    • @BionicCode 谢谢!现在我至少知道为什么会这样了。看起来尝试制作不泄漏的弱事件导致了一些未记录的意外副作用。
    • 对不起,我不同意。我认为您实现事件委托的方式会导致意想不到的副作用。您必须始终将事件的事件源设置为侦听器订阅的实际类。这是唯一有意义的方法。聚合的Model 是事件的原始来源这一事实是类内部结构,订阅者不知道。当您订阅 ClassA 的事件时,您会 100% 期望事件源也是 ClassA 而不是某个类的内部类型。 这会给听者带来意想不到的副作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    相关资源
    最近更新 更多