MetroWindow文本框数据验证

时间:2016-05-01 20:03:41

标签: c# wpf validation

我有这个带有IDataErrorInfo的ViewModel:

string _name;
public string name
{
    get { return this._name; }
    set
    {
        if (Equals(value, _name))
        {
            return;
        }
        _name= value;
        RaisePropertyChanged("Name");
    }
}

private static readonly string[] ValidatedProperties = {"Name"};
public event PropertyChangedEventHandler PropertyChanged;

protected virtual void RaisePropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

private string GetValidationError(string propertyName)
{
    string error = null;
    switch (propertyName)
    {
            case "Name":
            if (this.Name == String.Empty)
            {
                return "Please enter a name";
            }
            break;
    }
    return error;
}

public string this[string columnName]
{
    get { return GetValidationError(columnName); }
}

public bool IsValid
{
    get
    {
        foreach (string property in ValidatedProperties)
        {
            if (GetValidationError(property) != null)
            {
                return false;
            }
        }
        return true;
    }
}

public string Error { get { return string.Empty; } }

原始验证是整数< 10,我只是将所有内容都改为字符串并做错了,因为名称验证不起作用,我看不出问题。文本框:

<TextBox   
        Name="tekstas"
        Controls:TextBoxHelper.Watermark="Please enter a name"
        Text="{Binding Name, 
        ValidatesOnDataErrors=True, 
        UpdateSourceTrigger=PropertyChanged, 
        NotifyOnValidationError=True}"  
        Margin="104,197,47,104" />

这里有什么问题?

1 个答案:

答案 0 :(得分:0)

问题似乎与代码的这一部分有关。该函数应该返回一个字符串,而当不满足switch内部的情况时,有可能返回null。

private string GetValidationError(string propertyName)
{
    string error = null;
    switch (propertyName)
    {
            case "Name":
            if (this.Name == String.Empty)
            {
                return "Please enter a name";
            }
            break;

            default:
            error = "some text";
            break;
    }
return error;
}