Esempio n. 1
0
        /// <summary>
        /// Sets the known validation errors for a property.
        /// This may produce a prompt in the UI to correct
        /// the error before proceeding.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="dataErrors">The data errors.</param>
        public void SetPropertyErrors(
            string propertyName, IEnumerable <DataValidationError> dataErrors)
        {
            AssertArg.IsNotNullOrEmpty(propertyName, nameof(propertyName));

            bool raiseEvent = false;

            lock (errorsLock)
            {
                bool created = false;

                var errorsArray     = dataErrors as DataValidationError[] ?? dataErrors?.ToArray();
                int paramErrorCount = errorsArray?.Length ?? 0;

                if ((errorsField == null || errorsField.Count < 1) &&
                    paramErrorCount < 1)
                {
                    return;
                }

                if (errorsField == null)
                {
                    errorsField = new Dictionary <string, ObservableCollection <DataValidationError> >();
                    created     = true;
                }

                bool listFound = false;
                if (created || !(listFound = errorsField.TryGetValue(propertyName,
                                                                     out ObservableCollection <DataValidationError> list)))
                {
                    list = new ObservableCollection <DataValidationError>();
                }

                if (paramErrorCount < 1)
                {
                    if (listFound)
                    {
                        list?.Clear();
                        raiseEvent = true;
                    }
                }
                else
                {
                    var tempList = new List <DataValidationError>();

                    if (errorsArray != null)
                    {
                        foreach (var dataError in errorsArray)
                        {
                            if (created || list.SingleOrDefault(
                                    e => e.Id == dataError.Id) == null)
                            {
                                tempList.Add(dataError);
                                raiseEvent = true;
                            }
                        }
                    }

                    list.AddRange(tempList);
                    errorsField[propertyName] = list;
                }
            }

            if (raiseEvent)
            {
                OnErrorsChanged(propertyName);
            }
        }