【问题标题】:MVVM - Validating the model when a field in the viewmodel is changedMVVM - 在视图模型中的字段更改时验证模型
【发布时间】:2015-06-14 08:34:10
【问题描述】:

我将 MVVMLight 库与 Database-First EF 模型一起使用。当我的视图模型中的某个字段发生变化时,我不太清楚如何验证模型。当我在 set 方法中调用 Validate 时,这在我更新模型的各个属性时效果很好。我不确定这在其他地方是如何工作的。

举例来说,我的应用程序中有一个 Person 类(模型),在视图模型中实现了一个名为 Name 的属性:

private Person _currentPerson; 

// Code omitted...

[Required(ErrorMessage = "Name is a required field.")]
public string Name
{
    get { return _currentPerson.Name; }
    set
    {
        if (value != _currentPerson.Name)
        {
            _currentPerson.Name = value;
            RaisePropertyChanged();
            Validate(_currentPerson.Name);
        }
    }
}

当我想创建一个新人时,我有一个附加到 RelayCommand 的方法,名为 NewPerson,代码如下:

public RelayCommand NewCommand { get { return _newCommand ?? (_newCommand = new RelayCommand(NewPerson)); } }

// Code omitted...

private void NewPerson()
{
    _currentPerson = new Person();
    RaisePropertyChanged(String.Empty); // Updates model and UI.
}

我现在如何验证 _currentPerson 而无需在每个属性上调用 Validate?因为这个模型类有很多属性......(30+)。

我唯一尝试过的是使用反射来遍历 Person 对象的所有属性,但这一直导致我不太了解的异常。

更新: 设法让某些东西发挥作用,但必须有更好的方法来做到这一点:

private void NewPerson()
{
    _currentPerson = new Person();
    RaisePropertyChanged(String.Empty); // Updates model and UI.
    ValidatePerson(_currentPerson);
}

private void ValidatePerson(Person p)
{
    Validate(p.Forename, "Forename");
    Validate(p.Surname, "Surname");
    Validate(p.DateOfBirth, "DateOfBirth");
    // There's about another 30 calls to Validate here...
}

【问题讨论】:

    标签: c# wpf validation mvvm ef-database-first


    【解决方案1】:

    如何在 Validate() 方法中验证整个 person 对象,而不仅仅是单个属性?

    【讨论】:

    • 这不起作用,我得到以下异常:Additional information: The type 'PersonViewModel' does not contain a public property named 'ValidatePerson'.
    • 修复它,需要使用重载方法来防止该异常。
    【解决方案2】:

    如果您想按属性单独验证逻辑,只需添加一个单独的 validate all 方法,以便在整个模型需要检查时使用。这可以调用您的个人方法或执行更定制的操作。

    【讨论】:

    • 我是将这个方法放在视图模型中还是模型中,将验证方法添加到我的视图模型中会引发ArgumentException 和消息The type 'PersonViewModel' does not contain a public property named 'ValidatePerson'.
    • 对于它的价值,考虑到你已经标记了一个接受的答案,任何一个都可以。如果您希望该逻辑在其他地方可用,请将其放入模型中。如果验证特定于在该上下文中使用的模型,则将其放入视图模型中。
    猜你喜欢
    • 2018-06-30
    • 2011-04-04
    • 2012-11-14
    • 2010-11-18
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 2020-11-29
    相关资源
    最近更新 更多