验证

1.Exception

<TextBox Width="120" Text="{Binding Name,ValidatesOnExceptions=True,UpdateSourceTrigger=PropertyChanged}"
    ToolTip="{Binding  RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}">
</TextBox>

private string name;
public string Name
{    
    get
    {
        return name;
    }
    set
   {
        name = value;
        if (name.Length > 10)
        {
            throw new ArgumentException("输入超长!");
        }
   }
}

2.ValidationRule

<TextBox  Width="120" ToolTip="{Binding  RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}">
    <Binding Path="Name" UpdateSourceTrigger="PropertyChanged">
        <Binding.ValidationRules>
            <validate:CommonValidationRule  ValidateType="Name" xmlns:validate="clr-namespace:Demo_Prism.Validate"/>
        </Binding.ValidationRules>
    </Binding>
</TextBox>

验证规则类继承ValidationRule接口
namespace Demo_Prism.Validate
{
    public class CommonValidationRule : ValidationRule
    {
        private string validateType;

        public string ValidateType
        {
            get
            {
                return validateType;
            }
            set
            {
                validateType = value;
            }
        }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (ValidateType == "Name")
            {
                string s = (string)value;
                if (s.Length >10)
                {
                    return new ValidationResult(false, "输入超长!");
                }
            }
            return new ValidationResult(true, null);
        }
    }
}

3.IDataErrorInfo

<TextBox Width="120" Text="{Binding Name,ValidatesOnDataErrors=True,UpdateSourceTrigger=PropertyChanged}"
    ToolTip="{Binding  RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}">
</TextBox>

 

ViewModel继承IDataErrorInfo接口
public string Error
{
    get
    {
        return string.Empty;
    }
}

 public string this[string columnName]
 {
     get
     {
         string result = "";
         switch (columnName)
         {
             case "Name":
                 if (this.name != null && this.name.Length >10)
                     result = "输入超长";
                 break;
         }

         return result;
     }
 }


4.INotifyDataErrorInfo

<TextBox Width="120" Text="{Binding Name,ValidatesOnNotifyDataErrors=True,UpdateSourceTrigger=PropertyChanged}"
    ToolTip="{Binding  RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}">
</TextBox>

 

ViewModel继承INotifyDataErrorInfo接口

 public string Name
 {
     get
     {
         return name;
     }
     set
     {
         name = value;
         ValidateProperty(name);
     }
 }

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

public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

public bool HasErrors
{
    get
    {
        return _errors.Count > 0;
    }
}

public IEnumerable GetErrors(string propertyName)
{
    return _errors.ContainsKey(propertyName) ? _errors[propertyName] : null;
}

private void OnErrorsChanged(string propertyName)
{
    ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
}

private void ValidateProperty(object val, [CallerMemberName] string propertyName = null)
{
    ClearErrors(propertyName);
    if (propertyName == "Name")
    {
        if (val != null && val.ToString().Length > 10)
        {
            AddError(propertyName, "输入超长!");
        }
    }
}

private void AddError(string propertyName, string error)
{
    if (!_errors.ContainsKey(propertyName))
        _errors[propertyName] = new List<string>();

    if (!_errors[propertyName].Contains(error))
    {
        _errors[propertyName].Add(error);
        OnErrorsChanged(propertyName);
    }
}

private void ClearErrors(string propertyName)
{
    if (_errors.ContainsKey(propertyName))
    {
        _errors.Remove(propertyName);
        OnErrorsChanged(propertyName);
    }
}

5. 代码直接验证(直接用 MessageBox  弹出消息,Windows 的老传统)

 

https://www.cnblogs.com/cdaniu/p/16842897.html

posted @ 2023-10-19 18:26  zhangxiuju  阅读(78)  评论(0)    收藏  举报