繁体   English   中英

使用IDataErrorInfo的WPF MVVM验证

[英]WPF MVVM Validation Using IDataErrorInfo

我已经创建了需要验证的Person MVVM模型。 我正在使用IDataErrorInfo类并验证用户。 但是,当屏幕加载时,文本框已经为红色/有效状态,表明该字段需要填写。 我相信这是因为我在InitializeComponent中绑定了PersonViewModel。 我试图将LostFocus用于updatetriggers,但这没有做任何事情。

这是我的PersonViewModel:

 public class PersonViewModel : IDataErrorInfo
    {
        private string _firstName;
        private string _lastName; 

        public string LastName { get; set; }

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

        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value; }
        }



        public string this[string columnName]
        {
            get
            {
                string validationResult = String.Empty; 

                switch(columnName)
                {
                    case "FirstName":
                        validationResult = ValidateFirstName();
                        break; 

                    case "LastName":
                        validationResult = ValidateLastName();
                        break; 

                    default:
                        throw new ApplicationException("Unknown property being validated on the Product");
                }

                return validationResult; 
            }
        }

        private string ValidateLastName()
        {
            return String.IsNullOrEmpty(LastName) ? "Last Name cannot be empty" : String.Empty;
        }

        private string ValidateFirstName()
        {
            return String.IsNullOrEmpty(FirstName) ? "First Name cannot be empty" : String.Empty;
        }



    }

这是XAML:

  <StackPanel>
        <TextBlock>First Name</TextBlock>
        <TextBox Text="{Binding FirstName, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Background="Gray"></TextBox>
        <TextBlock>Last Name</TextBlock>
        <TextBox Text="{Binding LastName, ValidatesOnDataErrors=True, UpdateSourceTrigger=LostFocus}" Background="Gray"></TextBox>
    </StackPanel>

MainWindow.cs:

  public MainWindow()
        {
            InitializeComponent();


            _personViewModel = new PersonViewModel();

            this.DataContext = _personViewModel; 



        }

我想念什么吗? 我不希望在屏幕加载时触发验证。 我只希望在用户松开文本框的焦点时将其触发。

与其重新考虑默认情况下WPF的工作原理,不如考虑重新定义UI,以使错误显示“适合”屏幕加载以及数据输入错误的情况。 此外,用户应该以空白形式提示需要的内容。

创建一种方法来进行验证,并将验证结果存储在字典中:

private Dictionary<string, string> _validationErrors = new Dictionary<string, string>();

public void Validate(string propertyName)
{
    string validationResult = null;
    switch(propertyName)
    {
        case "FirstName":
            validationResult = ValidateFirstName();
            break; 
        }
        //etc.
    }

    //Clear dictionary properly here instead (You must also handle when a value becomes valid again)
    _validationResults[propertyName] = validationResult;
    //Note that in order for WPF to catch this update, you may need to raise the PropertyChanged event if you aren't doing so in the constructor (AFTER validating)
}

然后将您的ViewModel更新为:

  1. 让索引器返回_validationErrors的结果(如果存在)。
  2. 在设置器中调用Validate()。
  3. (可选)在Validate()中,如果propertyName为null,则验证所有属性。

WPF将调用索引器以显示错误,并且由于您正在返回某些内容,因此它将认为存在错误。 除非您使用此解决方案明确调用Validate(),否则不会这样做。

编辑:请注意,现在有一种更有效的方法在.NET 4.5中实现验证,称为INotifyDataErrorInfo

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM