Exemple #1
0
		internal static void AddError (FrameworkElement element, ValidationError error)
		{
			var errors = GetErrorsCore (element);
			errors.Add (error);
			if (errors.Count == 1)
				SetHasError (element, true);
		}
        /// <summary> 
        /// Constructor
        /// </summary> 
        internal ValidationErrorEventArgs(ValidationError validationError, ValidationErrorEventAction action) 
        {
            Invariant.Assert(validationError != null); 

            RoutedEvent = Validation.ErrorEvent;
            _validationError = validationError;
            _action = action; 
        }
        public static string CleanErrorMessage(ValidationError error)
        {
            if (error.Exception == null)
                return error.ErrorContent.ToString();

            if (error.Exception is TargetInvocationException)
                return error.Exception.InnerException.Message;

            return error.Exception.Message;
        }
Exemple #4
0
		internal static void AddError (FrameworkElement element, ValidationError error)
		{
			var errors = GetErrorsCore (element);
			errors.Add (error);
			if (errors.Count == 1)
				SetHasError (element, true);

			var control = element as Control;
			if (control != null)
				control.UpdateValidationState (false);
		}
Exemple #5
0
        // Based on exception handler from Josh Smith blog.
        public void Handler(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.ValidationErrorEventArgs args = e as System.Windows.Controls.ValidationErrorEventArgs;

            if (args.Error.RuleInError is System.Windows.Controls.ValidationRule)
            {
                if (ErrorContainer != null)
                {
                    Tracer.LogValidation("ViewBase.Handler called for ValidationRule exception.");

                    // Only want to work with validation errors that are Exceptions because the business object has already recorded the business rule violations using IDataErrorInfo.
                    BindingExpression bindingExpression = args.Error.BindingInError as System.Windows.Data.BindingExpression;
                    Debug.Assert(bindingExpression != null);

                    string           propertyName   = bindingExpression.ParentBinding.Path.Path;
                    DependencyObject OriginalSource = args.OriginalSource as DependencyObject;

                    // Construct the error message.
                    string errorMessage = "";
                    ReadOnlyObservableCollection <System.Windows.Controls.ValidationError> errors = System.Windows.Controls.Validation.GetErrors(OriginalSource);
                    if (errors.Count > 0)
                    {
                        StringBuilder builder = new StringBuilder();
                        builder.Append(propertyName).Append(":");
                        System.Windows.Controls.ValidationError error = errors[errors.Count - 1];
                        {
                            if (error.Exception == null || error.Exception.InnerException == null)
                            {
                                builder.Append(error.ErrorContent.ToString());
                            }
                            else
                            {
                                builder.Append(error.Exception.InnerException.Message);
                            }
                        }
                        errorMessage = builder.ToString();
                    }

                    // Add or remove the validation error to the validation error collection.
                    Debug.Assert(args.Action == ValidationErrorEventAction.Added || args.Action == ValidationErrorEventAction.Removed);
                    StringBuilder errorID = new StringBuilder();
                    errorID.Append(args.Error.RuleInError.ToString());
                    if (args.Action == ValidationErrorEventAction.Added)
                    {
                        ErrorContainer.AddError(new ValidationToolkit.ValidationError(propertyName, errorID.ToString(), errorMessage));
                    }
                    else if (args.Action == ValidationErrorEventAction.Removed)
                    {
                        ErrorContainer.RemoveError(propertyName, errorID.ToString());
                    }
                }
            }
        }
        private void AddError(object validationSource, ValidationError error)
        {
            errors.Add(new Tuple<object, ValidationError>(validationSource, error));

            if (validationSource is FrameworkElement)
            {
                ((FrameworkElement)validationSource).Unloaded += ValidationSourceUnloaded;
            }
            else if (validationSource is FrameworkContentElement)
            {
                ((FrameworkContentElement)validationSource).Unloaded += ValidationSourceUnloaded;
            }
        }
        public void ShouldReturnTheErrorContentOfTheFirstItemInTheCollection()
        {
            ErrorConverter converter = new ErrorConverter();

            List<ValidationError> errors = new List<ValidationError>();
            ValidationError error = new ValidationError(new ExceptionValidationRule(), new object());
            error.ErrorContent = "TestError";
            errors.Add(error);

            object result = converter.Convert(errors.AsReadOnly(), null, null, null);

            Assert.AreEqual("TestError", result);
        }
        public void ShouldReturnTheInnerExceptionMessageOfATargetInvocationException()
        {
            ErrorConverter converter = new ErrorConverter();

            List<ValidationError> errors = new List<ValidationError>();
            ValidationError error = new ValidationError(new ExceptionValidationRule(), new object());
            error.Exception = new TargetInvocationException(null, new Exception("TestError"));
            errors.Add(error);

            object result = converter.Convert(errors.AsReadOnly(), null, null, null);

            Assert.AreEqual("TestError", result);
        }
Exemple #9
0
        public SelectSourceView()
        {
            InitializeComponent();
            this.Loaded += (s, e) =>
            {
                var monthExpr = this.SelectMonth.GetBindingExpression(ComboBox.SelectedValueProperty);
                var monthErr  = new ValidationError(new RequiredRule(), monthExpr);
                Validation.MarkInvalid(monthExpr, monthErr);

                var yearExpr = this.SelectYear.GetBindingExpression(ComboBox.SelectedValueProperty);
                var yearErr  = new ValidationError(new RequiredRule(), yearExpr);
                Validation.MarkInvalid(yearExpr, yearErr);
            };
        }
        private static bool IsScopeFor(this DependencyObject parent, ValidationError error)
        {
            var inputTypes = GetForInputTypes(parent as FrameworkElement);
            if (inputTypes == null)
            {
                return false;
            }

            if (inputTypes.Contains(typeof(Scope)))
            {
                return true;
            }

            return inputTypes.Contains(error.Target());
        }
        /// <summary>
        /// Método que verifica se o campo está vazio, deve ser vinculado com 
        /// LostFocus para ativa-lo
        /// </summary>
        public static void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            TextBox textBox = (TextBox)sender;
            if (textBox.Text == "")
            {
                ValidationError validationError =
                new ValidationError(new ValidacaoNotNull(),
                textBox.GetBindingExpression(TextBox.TextProperty));

                validationError.ErrorContent = "O campo não pode ser nulo";

                Validation.MarkInvalid(
                    textBox.GetBindingExpression(TextBox.TextProperty),
                    validationError);
            }
        }
Exemple #12
0
        // remove a validation error from the given element
        internal static void RemoveValidationError(ValidationError validationError, DependencyObject targetElement, bool shouldRaiseEvent) 
        {
            if (targetElement == null) 
                return; 

            ValidationErrorCollection validationErrors = GetErrorsInternal(targetElement); 
            if (validationErrors == null || validationErrors.Count == 0 || !validationErrors.Contains(validationError))
                return;

            bool isValid = (validationErrors.Count == 1);   // about to remove the last error 

            if (isValid) 
            { 
                // instead of removing the last error, just discard the error collection.
                // This sends out only one property-change event, instead of two. 
                // Any bindings to Errors[x] will appreciate the economy.
                targetElement.ClearValue(HasErrorPropertyKey);

                targetElement.ClearValue(ValidationErrorsInternalProperty); 

                if (shouldRaiseEvent) 
                { 
                    OnValidationError(targetElement, validationError, ValidationErrorEventAction.Removed);
                } 

                ShowValidationAdorner(targetElement, false);
            }
            else 
            {
                // if it's not the last error, just remove it. 
                validationErrors.Remove(validationError); 

                if (shouldRaiseEvent) 
                {
                    OnValidationError(targetElement, validationError, ValidationErrorEventAction.Removed);
                }
            } 
        }
Exemple #13
0
        // add a validation error to the given element
        internal static void AddValidationError(ValidationError validationError, DependencyObject targetElement, bool shouldRaiseEvent)
        {
            if (targetElement == null) 
                return;
 
            bool wasValid; 
            ValidationErrorCollection validationErrors = GetErrorsInternal(targetElement);
 
            if (validationErrors == null)
            {
                wasValid = true;
                validationErrors = new ValidationErrorCollection(); 
                validationErrors.Add(validationError);
                targetElement.SetValue(Validation.ValidationErrorsInternalProperty, validationErrors); 
            } 
            else
            { 
                wasValid = (validationErrors.Count == 0);
                validationErrors.Add(validationError);
            }
 
            if (wasValid)
            { 
                targetElement.SetValue(HasErrorPropertyKey, BooleanBoxes.TrueBox); 
            }
 
            if (shouldRaiseEvent)
            {
                OnValidationError(targetElement, validationError, ValidationErrorEventAction.Added);
            } 

            if (wasValid) 
            { 
                ShowValidationAdorner(targetElement, true);
            } 
        }
Exemple #14
0
		void MaybeEmitError (object message, Exception exception)
		{
			// If we've databound to a DependencyObject we need to emit
			// the error on the Mentor, if it has one.
			var fe = Target as FrameworkElement ?? Target.Mentor;
			if (fe == null) {
				return;
			}

			if (message is string && (string) message == "")
				message = null;

			var oldError = CurrentError;
			if (message != null)
				CurrentError = new ValidationError (message, null);
			else if (exception != null)
				CurrentError = new ValidationError (null, exception);
			else
				CurrentError = null;

			// We had an error and now we have a new error
			if (oldError != null && CurrentError != null) {
				Validation.AddError (fe, CurrentError);
				Validation.RemoveError (fe, oldError);
				if (Binding.NotifyOnValidationError) {
					fe.RaiseBindingValidationError (new ValidationErrorEventArgs(ValidationErrorEventAction.Removed, oldError));
					fe.RaiseBindingValidationError (new ValidationErrorEventArgs(ValidationErrorEventAction.Added, CurrentError));
				}
			} else if (oldError != null) {
				Validation.RemoveError (fe, oldError);
				if (Binding.NotifyOnValidationError)
					fe.RaiseBindingValidationError (new ValidationErrorEventArgs(ValidationErrorEventAction.Removed, oldError));
			} else if (CurrentError != null) {
				Validation.AddError (fe, CurrentError);
				if (Binding.NotifyOnValidationError)
					fe.RaiseBindingValidationError (new ValidationErrorEventArgs(ValidationErrorEventAction.Added, CurrentError));
			}
		}
Exemple #15
0
 internal ValidationErrorEventArgs(ValidationErrorEventAction action, ValidationError error)
 {
     this.action = action;
     this.error  = error;
 }
        private void SetError(TextBox textBox, string error)
        {
            var textBoxBindingExpression = textBox.GetBindingExpression(TextBox.TextProperty);
            if (textBoxBindingExpression == null) return;
            ValidationError validationError =
                new ValidationError(new RequiredValidationRule(),
                    textBoxBindingExpression) {ErrorContent = error};


            Validation.MarkInvalid(
                textBoxBindingExpression,
                validationError);
        }
Exemple #17
0
        private void dataGrid_CellValueChanged(object sender, Control.DataGridCellEditEndingEventArgs e)
        {
            if (e.EditAction == Control.DataGridEditAction.Commit)
            {
                WPFdataGrid.DataGridControl wPFdataGrid = elementHost1.Child as WPFdataGrid.DataGridControl;
                var dataGridView = wPFdataGrid.grid;

                Control.DataGridRow          dataRow    = e.Row as Control.DataGridRow;
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(dataRow.Item);

                DataGridDetailsPresenter presenter = FindVisualChild <DataGridDetailsPresenter>(dataRow);
                DataTemplate             detail    = presenter.ContentTemplate;

                Int16.TryParse(properties["HP"].GetValue(dataRow.Item).ToString(), out Int16 HP);
                Int16.TryParse(properties["Attack"].GetValue(dataRow.Item).ToString(), out Int16 Attack);
                Int16.TryParse(properties["Defense"].GetValue(dataRow.Item).ToString(), out Int16 Defense);
                Int16.TryParse(properties["SPAttack"].GetValue(dataRow.Item).ToString(), out Int16 SPAttack);
                Int16.TryParse(properties["SPDefense"].GetValue(dataRow.Item).ToString(), out Int16 SPDefense);
                Int16.TryParse(properties["Speed"].GetValue(dataRow.Item).ToString(), out Int16 Speed);

                Int16 CapRate = 0;
                Int16 ExpDrop = 0;

                try
                {
                    Control.DataGrid detailGrid = detail.FindName("details", presenter) as Control.DataGrid;

                    PropertyDescriptorCollection detailProperties = TypeDescriptor.GetProperties(detailGrid.Items.CurrentItem);

                    Int16.TryParse(detailProperties["CapRate"]?.GetValue(detailGrid.Items?.CurrentItem)?.ToString(), out CapRate);
                    Int16.TryParse(detailProperties["ExpDrop"]?.GetValue(detailGrid.Items?.CurrentItem)?.ToString(), out ExpDrop);
                }
                catch
                {
                    using (Pokemon db = new Pokemon())
                    {
                        try
                        {
                            CapRate = db.PokemonBaseStats.Where(p => p.PName == properties["PName"].GetValue(dataRow.Item).ToString()).Single().PokemonCapRate.CapRate;
                            ExpDrop = db.PokemonBaseStats.Where(p => p.PName == properties["PName"].GetValue(dataRow.Item).ToString()).Single().PokemonCapRate.ExpDrop;
                        }
                        catch
                        {
                            CapRate = 0;
                            ExpDrop = 0;
                        }
                    }
                }

                pokemon = new PokemonBaseStat()
                {
                    PName     = properties["PName"].GetValue(dataRow.Item)?.ToString(),
                    HP        = HP,
                    Attack    = Attack,
                    Defense   = Defense,
                    SPAttack  = SPAttack,
                    SPDefense = SPDefense,
                    Speed     = Speed,
                    Type1     = properties["Type1"].GetValue(dataRow.Item)?.ToString(),
                    Type2     = properties["Type2"].GetValue(dataRow.Item)?.ToString(),

                    PokemonCapRate = new PokemonCapRate()
                    {
                        PName   = properties["PName"].GetValue(dataRow.Item)?.ToString(),
                        CapRate = CapRate,
                        ExpDrop = ExpDrop
                    }
                };

                ValidationContext        validate = new ValidationContext(pokemon, null, null);
                IList <ValidationResult> errors   = new List <ValidationResult>();

                if (!Validator.TryValidateObject(pokemon, validate, errors, true))
                {
                    e.Cancel         = true;
                    EventArgs.Cancel = true;
                    EventArgs.Error  = null;

                    Control.DataErrorValidationRule validationRule = new Control.DataErrorValidationRule();

                    Control.ValidationError error = new Control.ValidationError(validationRule, dataRow.BindingGroup.BindingExpressions);

                    EventArgs.Error = $"{errors.First().ErrorMessage}";

                    error.ErrorContent = $"{errors.First().ErrorMessage}";

                    foreach (ValidationResult result in errors.Skip(1))
                    {
                        EventArgs.Error += $"\n{result.ErrorMessage}";

                        error.ErrorContent += $"\n{result.ErrorMessage}";
                    }

                    foreach (var binding in dataRow.BindingGroup.BindingExpressions)
                    {
                        Control.Validation.MarkInvalid(dataRow.BindingGroup.BindingExpressions.First(), error);
                    }
                }
                else
                {
                    Control.DataErrorValidationRule validationRule = new Control.DataErrorValidationRule();

                    Control.ValidationError error = new Control.ValidationError(validationRule, dataRow.BindingGroup.BindingExpressions);

                    e.Cancel           = false;
                    EventArgs.Cancel   = false;
                    error.ErrorContent = null;
                }
            }
        }
 ValidationErrorEventArgs CreateValidationErrorEventArgs(ValidationError error, ValidationErrorEventAction action) {
     ConstructorInfo constructor = typeof(ValidationErrorEventArgs).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(ValidationError), typeof(ValidationErrorEventAction) }, null);
     return (ValidationErrorEventArgs)constructor.Invoke(new object[] { error, action });
 }
Exemple #19
0
        private void detailGrid_CellValueChanged(object sender, Control.DataGridCellEditEndingEventArgs e)
        {
            if (e.EditAction == Control.DataGridEditAction.Commit)
            {
                WPFdataGrid.DataGridControl wPFdataGrid = elementHost1.Child as WPFdataGrid.DataGridControl;
                var dataGridView = wPFdataGrid.grid;

                Control.DataGridRow dataRow = e.Row as Control.DataGridRow;

                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(dataRow.Item);

                Int16.TryParse(properties["CapRate"]?.GetValue(dataRow.Item)?.ToString(), out Int16 CapRate);
                Int16.TryParse(properties["ExpDrop"]?.GetValue(dataRow.Item)?.ToString(), out Int16 ExpDrop);

                pokemonCapRate = new PokemonCapRate()
                {
                    PName   = properties["PName"].GetValue(dataRow.Item)?.ToString(),
                    CapRate = CapRate,
                    ExpDrop = ExpDrop
                };

                ValidationContext        validate = new ValidationContext(pokemonCapRate, null, null);
                IList <ValidationResult> errors   = new List <ValidationResult>();

                if (!Validator.TryValidateObject(pokemonCapRate, validate, errors, true))
                {
                    e.Cancel         = true;
                    EventArgs.Cancel = true;
                    EventArgs.Error  = null;

                    Control.DataErrorValidationRule validationRule = new Control.DataErrorValidationRule();

                    Control.ValidationError error = new Control.ValidationError(validationRule, dataRow.BindingGroup.BindingExpressions);

                    EventArgs.Error = $"{errors.First().ErrorMessage}";

                    error.ErrorContent = $"{errors.First().ErrorMessage}";

                    foreach (ValidationResult result in errors.Skip(1))
                    {
                        EventArgs.Error += $"\n{result.ErrorMessage}";

                        error.ErrorContent += $"\n{result.ErrorMessage}";
                    }

                    foreach (var binding in dataRow.BindingGroup.BindingExpressions)
                    {
                        Control.Validation.MarkInvalid(dataRow.BindingGroup.BindingExpressions.First(), error);
                    }
                }
                else
                {
                    Control.DataErrorValidationRule validationRule = new Control.DataErrorValidationRule();

                    Control.ValidationError error = new Control.ValidationError(validationRule, dataRow.BindingGroup.BindingExpressions);

                    e.Cancel           = false;
                    EventArgs.Cancel   = false;
                    error.ErrorContent = null;

                    pokemonCapRates.Add(pokemonCapRate);
                }
            }
        }
Exemple #20
0
		internal ValidationErrorEventArgs (ValidationErrorEventAction action, ValidationError error)
		{
			this.action = action;
			this.error = error;
		}
		void ValidateSearchText(object sender, RoutedEventArgs e)
		{
			var be = searchTextBox.GetBindingExpression(TextBox.TextProperty);
			try {
				Validation.ClearInvalid(be);
				UpdateSearch();
			} catch (SearchPatternException ex) {
				var ve = new ValidationError(be.ParentBinding.ValidationRules[0], be, ex.Message, ex);
				Validation.MarkInvalid(be, ve);
			}
		}
        internal void RemoveValidationError(ValidationError validationError)
        {
            // remove the error from the target element
            Validation.RemoveValidationError(validationError, TargetElement, NotifyOnValidationError); 

            // remove the error from the binding group's target element 
            BindingGroup bindingGroup = BindingGroup; 
            if (bindingGroup != null)
            { 
                bindingGroup.RemoveValidationError(validationError);
            }
        }
        internal void AddValidationError(ValidationError validationError) 
        { 
            // add the error to the target element
            Validation.AddValidationError(validationError, TargetElement, NotifyOnValidationError); 

            // add the error to the binding group's target element
            BindingGroup bindingGroup = BindingGroup;
            if (bindingGroup != null) 
            {
                bindingGroup.AddValidationError(validationError); 
            } 
        }
        internal void UpdateValidationError(ValidationError validationError)
        { 
            // the steps are carefully ordered to avoid going through a "no error" 
            // state while replacing one error with another
            ValidationError oldValidationError = _validationError; 

            _validationError = validationError;

            if (validationError != null) 
            {
                AddValidationError(_validationError); 
            } 

            if (oldValidationError != null) 
            {
                RemoveValidationError(oldValidationError);
            }
        } 
Exemple #25
0
        static void OnValidationError(DependencyObject source, ValidationError validationError, ValidationErrorEventAction action) 
        {
            ValidationErrorEventArgs args = new ValidationErrorEventArgs(validationError, action); 

            if (source is ContentElement)
                ((ContentElement)source).RaiseEvent(args);
            else if (source is UIElement) 
                ((UIElement)source).RaiseEvent(args);
            else if (source is UIElement3D) 
                ((UIElement3D)source).RaiseEvent(args); 
        }
        // return the value for the initial data transfer.  Specifically:
        //      normal case - return UnsetValue (we'll get the value from the source object)
        //      valid proposed value - return the proposed value
        //      invalid proposed value - two subcases:
        //          one-way binding - return default/fallback value
        //          two-way binding - retrun NullDataItem (meaning "don't transfer")
        //
        //      In both subcases, adopt the validation errors discovered earlier.
        //      In the two-way subcase, instead of a source-to-target transfer, we set the
        //      the target property to the (saved) raw proposed value, as if the user
        //      had edited this property.
        object GetInitialValue(DependencyObject target, out ValidationError error)
        {
            object proposedValue;

            // find the binding group this binding would join if it were two-way (even if it isn't)
            BindingGroup bindingGroup = RootBindingExpression.FindBindingGroup(true, ContextElement);
            BindingGroup.ProposedValueEntry entry;

            // get the proposed value from the binding group
            if (bindingGroup == null ||
                (entry = bindingGroup.GetProposedValueEntry(SourceItem, SourcePropertyName)) == null)
            {
                // no proposed value
                error = null;
                proposedValue = DependencyProperty.UnsetValue;
            }
            else
            {
                // adopt the validation error (possibly null)
                error = entry.ValidationError;

                if (IsReflective && TargetProperty.IsValidValue(entry.RawValue))
                {
                    // two-way binding - set the target property directly
                    target.SetValue(TargetProperty, entry.RawValue);
                    proposedValue = NullDataItem;
                    bindingGroup.RemoveProposedValueEntry(entry);
                }
                else if (entry.ConvertedValue == DependencyProperty.UnsetValue)
                {
                    // invalid proposed value - use fallback/default
                    proposedValue = UseFallbackValue();
                }
                else
                {
                    // valid proposed value
                    proposedValue = entry.ConvertedValue;
                }

                // if this binding didn't take over responsibility for the proposed
                // value, add it to the list of bindings using the proposed value
                if (proposedValue != NullDataItem)
                {
                    bindingGroup.AddBindingForProposedValue(this, SourceItem, SourcePropertyName);
                }
            }

            return proposedValue;
        }
        /// <summary>
        /// Validates all properties on the current data source.
        /// </summary>
        /// <returns>True if there are no errors displayed, otherwise false.</returns>
        /// <remarks>
        /// Note that only errors on properties that are displayed are included. Other errors, such as errors for properties that are not displayed, 
        /// will not be validated by this method.
        /// </remarks>
        public bool Validate()
        {
            bool isValid = true;
            _firstInvalidElement = null;

            if (this.DataContext is IDataErrorInfo)
            {
                List<Binding> allKnownBindings = ClearInternal();

                // Now show all errors
                foreach (Binding knownBinding in allKnownBindings)
                {
                    string errorMessage = ((IDataErrorInfo)this.DataContext)[knownBinding.Path.Path];
                    if (errorMessage != null && errorMessage.Length > 0)
                    {
                        isValid = false;

                        // Display the error on any elements bound to the property
                        FindBindingsRecursively(
                        this.Parent,
                        delegate(FrameworkElement element, Binding binding, DependencyProperty dp)
                        {
                            if (knownBinding.Path.Path == binding.Path.Path)
                            {

                                BindingExpression expression = element.GetBindingExpression(dp);
                                ValidationError error = new ValidationError(new ExceptionValidationRule(), expression, errorMessage, null);
                                System.Windows.Controls.Validation.MarkInvalid(expression, error);

                                if (_firstInvalidElement == null)
                                {
                                    _firstInvalidElement = element;
                                }
                                return;

                            }
                        });
                    }
                }
            }
            return isValid;
        }
        ValidationError RunValidationRule(ValidationRule validationRule, object value, CultureInfo culture)
        {
            ValidationError error;

            ValidationResult validationResult = validationRule.Validate(value, culture, this);

            if (validationResult.IsValid)
            {
                error = null;
            }
            else
            {
                if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Update))
                {
                    TraceData.Trace(TraceEventType.Warning,
                                        TraceData.ValidationRuleFailed(
                                            TraceData.Identify(this),
                                            TraceData.Identify(validationRule)));
                }

                error = new ValidationError(validationRule, this, validationResult.ErrorContent, null);
            }

            return error;
        }
		void ValidateSearchText()
		{
			if (searchTextBox == null)
				return;
			var be = searchTextBox.GetBindingExpression(TextBox.TextProperty);
			try {
				Validation.ClearInvalid(be);
				UpdateSearch();
			} catch (SearchPatternException ex) {
				var ve = new ValidationError(be.ParentBinding.ValidationRules[0], be, ex.Message, ex);
				Validation.MarkInvalid(be, ve);
			}
		}
        internal override object ConvertProposedValue(object value)
        {
            object rawValue = value;
            bool isExtendedTraceEnabled = TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Update);
            if (isExtendedTraceEnabled)
            {
                TraceData.Trace(TraceEventType.Warning,
                                    TraceData.UpdateRawValue(
                                        TraceData.Identify(this),
                                        TraceData.Identify(value)));
            }

            Type sourceType = Worker.SourcePropertyType;
            IValueConverter implicitConverter = null;
            CultureInfo culture = GetCulture();

            // apply user-defined converter
            if (Converter != null)
            {
                if (!UseDefaultValueConverter)
                {
                    // if there's a user-defined converter, call it without catching
                    // exceptions (bug 992237).  It can return DependencyProperty.UnsetValue
                    // to indicate a failure to convert.
                    value = Converter.ConvertBack(value, sourceType, ParentBinding.ConverterParameter, culture);

                    if (IsDetached)
                    {
                        // user code detached the binding.  Give up.
                        return Binding.DoNothing;
                    }

                    if (isExtendedTraceEnabled)
                    {
                        TraceData.Trace(TraceEventType.Warning,
                                            TraceData.UserConvertBack(
                                                TraceData.Identify(this),
                                                TraceData.Identify(value)));
                    }

                    // chain in a default value converter if the returned value's type is not compatible with the sourceType
                    if (value != Binding.DoNothing && value != DependencyProperty.UnsetValue &&
                        !IsValidValueForUpdate(value, sourceType))
                    {
                        // the dynamic converter is shared between Transfer and Update directions
                        // once instantiated, DefaultValueConverters are kept in a lookup table, making swapping
                        // default value converters reasonably fast
                        implicitConverter = DynamicConverter;
                    }
                }
                else
                {
                    implicitConverter = Converter;
                }
            }

            // apply an implicit conversion, if needed.  This can be
            //  a) null conversion
            //  b) type conversion
            if (value != Binding.DoNothing && value != DependencyProperty.UnsetValue)
            {
                if (IsNullValue(value))
                {
                    if (value == null || !IsValidValueForUpdate(value, sourceType))
                    {
                        if (Worker.IsDBNullValidForUpdate)
                        {
                            value = DBNull.Value;
                        }
                        else
                        {
                            value = NullValueForType(sourceType);
                        }
                    }
                }
                else if (implicitConverter != null)
                {
                    // here we pass in the TargetElement, see NOTE of caution in TransferValue() why this is ok
                    value = ConvertBackHelper(implicitConverter, value, sourceType, this.TargetElement, culture);

                    if (isExtendedTraceEnabled)
                    {
                        TraceData.Trace(TraceEventType.Warning,
                                            TraceData.DefaultConvertBack(
                                                TraceData.Identify(this),
                                                TraceData.Identify(value)));
                    }
                }
            }

            if (isExtendedTraceEnabled)
            {
                TraceData.Trace(TraceEventType.Warning,
                                    TraceData.Update(
                                        TraceData.Identify(this),
                                        TraceData.Identify(value)));
            }

            // if the conversion failed, signal a validation error
            if (value == DependencyProperty.UnsetValue)
            {
                if (ValidationError == null)
                {
                    ValidationError validationError = new ValidationError(ConversionValidationRule.Instance, this, SR.Get(SRID.Validation_ConversionFailed, rawValue), null);
                    UpdateValidationError(validationError);
                }
            }

            return value;
        }
        void ShowValidateError(bool showError)
        {
            IsShowingMessage = showError;

            if (ValidatesControl == null || !IsAdornerEnabled()) return;

            var bindingExpression = ValidatesControl.GetBindingExpression(TextBox.TagProperty);
            if (bindingExpression == null) return;
            var opExpression = BindingOperations.GetBindingExpression(ValidatesControl, TextBox.TagProperty);
            if (opExpression == null) return;
            var validationError = new ValidationError(new ExceptionValidationRule(), opExpression);

            if (showError)
            {
                validationError.ErrorContent = Text;
                System.Windows.Controls.Validation.MarkInvalid(bindingExpression, validationError);
            }
            else
            {
                System.Windows.Controls.Validation.ClearInvalid(bindingExpression);
            }
        }
        private void ProcessException(Exception ex, bool validate)
        {
            object filteredException = null;
            ValidationError validationError = null;

            // If there is not ExceptionFilter, then Wrap the
            // exception in a ValidationError.
            if (ExceptionFilterExists())
            {
                filteredException = CallDoFilterException(ex);

                if (filteredException == null)
                    return;

                validationError = filteredException as ValidationError;
            }

            // See if an ExceptionValidationRule is in effect
            if (validationError == null && validate)
            {
                ValidationRule exceptionValidationRule = ExceptionValidationRule.Instance;

                if (filteredException == null)
                {
                    validationError = new ValidationError(exceptionValidationRule, this, ex.Message, ex);
                }
                else
                {
                    validationError = new ValidationError(exceptionValidationRule, this, filteredException, ex);
                }
            }

            if (validationError != null)
            {
                UpdateValidationError(validationError);
            }
        }
 public static void MarkInvalid(System.Windows.Data.BindingExpressionBase bindingExpression, ValidationError validationError)
 {
 }
Exemple #34
0
        /// <summary>
        /// Mark this BindingExpression as invalid.  If the BindingExpression has been
        /// explicitly marked invalid in this way, then it will remain 
        /// invalid until ClearInvalid is called or another transfer to the source validates successfully.
        /// </summary> 
        public static void MarkInvalid(BindingExpressionBase bindingExpression, ValidationError validationError) 
        {
            if (bindingExpression == null) 
                throw new ArgumentNullException("bindingExpression");
            if (validationError == null)
                throw new ArgumentNullException("validationError");
 
            bindingExpression.UpdateValidationError(validationError);
        } 
Exemple #35
0
        /// <summary>
        /// Validates all properties on the current data source.
        /// </summary>
        /// <returns>True if there are no errors displayed, otherwise false.</returns>
        /// <remarks>
        /// Note that only errors on properties that are displayed are included. Other errors, such as errors for properties that are not displayed, 
        /// will not be validated by this method.
        /// </remarks>
        protected bool Validate()
        {
            bool isValid = true;
            _firstInvalidElement = null;
            errorMessages = new List<string>();

            BindingHelper.FindBindingsRecursively(Parent,
                                    delegate(FrameworkElement element, Binding binding, DependencyProperty dp)
                                    {
                                        foreach (ValidationRule rule in binding.ValidationRules)
                                        {
                                            ValidationResult valid = rule.Validate(element.GetValue(dp), CultureInfo.CurrentUICulture);
                                            if (!valid.IsValid)
                                            {
                                                if (isValid)
                                                {
                                                    isValid = false;
                                                    _firstInvalidElement = element;
                                                }

                                                BindingExpression expression = element.GetBindingExpression(dp);
                                                ValidationError error = new ValidationError(rule, expression, valid.ErrorContent, null);
                                                Validation.MarkInvalid(expression, error);

                                                string errorMessage = valid.ErrorContent.ToString();
                                                if (!errorMessages.Contains(errorMessage))
                                                    errorMessages.Add(errorMessage);
                                            }
                                        }
                                    });

            return isValid;
        }
 public BubbleErrorValidationRule(ValidationError error)
 {
     _error = error;
 }