关于c#:数据类型验证以及IDataErrorInfo

Data type validation alongside IDataErrorInfo

我刚刚开始向WPF MVVM项目添加一些验证。对我来说,这种范例验证是新手,但似乎相当简单:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public partial class Price : IDataErrorInfo
{
    public double Cost { get; set; }

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

    string IDataErrorInfo.this[string columnName]
    {
        get
        {
            string message = null;
            if (columnName =="Cost" && this.Cost > 10000.00)
            {
                message ="This price is high enough to require confirmation";
            }
            return message;
        }
    }
}

Cost属性在ViewModel中绑定到一个文本框,允许用户输入自己的数据。在实施IDataErrorInfo之前,用户在此框中键入文本会导致该文本以红色突出显示,但未显示任何错误消息。这被认为是足够的警告。

现在,在文本框中输入文字会显示我实现的样式,以显示错误,这很好。另外还有一条消息:值''无法转换,但是对于用户来说有点保守。真正的问题是,如果有人键入大于10000.00的数字并触发自定义消息,然后删除该值并用文本替换它,则旧的错误消息会保留在原位。

有了断点,就可以清楚地知道正在发生什么:因为View期望它是double值,所以它甚至不必检查IDataErrorInfo是否已更改。如何清除错误消息并用更有意义的内容替换?我无法解析Cost,因为它是两倍,所以如果有人输入文本,它甚至都不会被设置?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 public class Price : IDataErrorInfo
{
    private double _costDouble;

    private string _cost;
    public string Cost
    {
        get {
            return _cost;
        }
        set {
                _cost = value;
                double.TryParse(value, out _costDouble);
            }
    }

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

    string IDataErrorInfo.this[string columnName]
    {
        get
        {
            string message = null;
            if (columnName =="Cost")
            {
                double doubleVal;
                if (double.TryParse(this.Cost, out doubleVal))
                {
                    if (doubleVal > 1000.0)
                        message ="This price is high enough to require confirmation";
                }
                else {
                    message ="Format error";
                }
            }
            return message;
        }
    }
}

您最终必须使用String-Property来绑定到文本框。

奖励:现在,您可以验证用户是否输入数字值。


最好的方法是将Cost属性的类型更改为字符串,然后尝试在验证回调中对其进行解析。 使用此方法,无需在XAML中使用任何ValidationRules,只需使用IDataErrorInfo。

可以在这篇文章中找到更多信息:Josh Smith,网址为https://joshsmithonwpf.wordpress.com/2008/11/14/using-a-viewmodel-to-provide-有意义-验证-错误消息-。

干杯