【问题标题】:WPF/Caliburn.Micro - Input Validation using IDataErrorInfoWPF/Caliburn.Micro - 使用 IDataErrorInfo 进行输入验证
【发布时间】:2015-11-04 14:03:02
【问题描述】:

我的 WPF 应用程序中有以下代码,我正在尝试实现输入验证。

型号:

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

视图模型:

public class CustomerViewModel : Screen, IDataErrorInfo
{
    private Customer _customer;
    public Customer Customer
    {
        get { return _customer; }
        set
        {
            if (_customer != value)
            {
                _customer = value;
                NotifyOfPropertyChange(() => Customer);
            }
        }
    }

    public string Error
    {
        get
        {
            throw new NotImplementedException();
        }
    }

    public string this[string columnName]
    {
        get
        {
            string result = null;
            if (columnName == "Name")
            {
                if (string.IsNullOrEmpty(Customer.Name))
                    result = "Please enter a Name";
                if (Customer.Name.Length < 3)
                    result = "Name is too short";
            }
            return result;
        }
    }
}

查看:

<TextBox Text="{Binding Customer.Name, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=true, NotifyOnValidationError=true}"/>

问题: 该解决方案未按预期工作。在文本框中键入数据时没有任何反应。我不确定我是否采取了正确的步骤。

谁能帮帮我?

【问题讨论】:

  • 试试UpdateSourceTrigger=PropertyChanged怎么样?

标签: c# wpf mvvm caliburn.micro idataerrorinfo


【解决方案1】:

我认为问题的发生是因为您的视图模型中没有 Name 属性(但在 Customer 类中)。 您在绑定 Customer.Name 中使用嵌套属性。

我没有将它与IDataErrorInfo 验证结合使用。

目前您的视图模型索引器内部的这个条件不会被命中:

if (columnName == "Name")
{
...
}

因为永远不会调用索引器。


我的建议

Name 属性添加到您的视图模型中,该属性将代表客户名称。 然后,您可以使用客户类(如设置)初始化您的视图模型

Name = customer.Name

在视图模型构造函数中。

您的绑定需要更改为

<TextBox Text="{Binding Name  ....

完成此操作后,索引器应该可以工作了,因为现在您的视图模型中有一个 Name 属性。

也许还有另一种解决方案可以让您保持当前的嵌套绑定 (Customer.Name),但我不确定这一点。

【讨论】:

  • 很确定这是这种情况,因为客户没有继承 INotifyDataErrorInfo/IDataErrorInfo,错误处理不会冒泡。如果您在 viewmodel 路线之上使用模型路线,则需要两倍的代码。 ConventionManager 中内置的约定显式查找 INotifyDataErrorInfo/IDataErrorInfo 接口并将 ValidatesOnError 和 NotifyOnValidationErrors 绑定为 true。使用视图模型中的属性进行验证,然后将结果分配给相关对象更容易。
猜你喜欢
  • 2014-05-23
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-30
  • 1970-01-01
相关资源
最近更新 更多