private void Target_BindingValidationError(object sender, ValidationErrorEventArgs e) { FrameworkElement inputControl = e.OriginalSource as FrameworkElement; if (e != null && e.Error != null && e.Error.ErrorContent != null && inputControl != null) { string message = e.Error.ErrorContent.ToString(); string key = String.IsNullOrEmpty(inputControl.Name) ? inputControl.GetHashCode().ToString(CultureInfo.InvariantCulture) : inputControl.Name; key += message; if (this._validationSummaryItemDictionary.ContainsKey(key)) { ValidationSummaryItem existingError = this._validationSummaryItemDictionary[key]; this._errors.Remove(existingError); this._validationSummaryItemDictionary.Remove(key); } if (e.Action == ValidationErrorEventAction.Added) { if (GetShowErrorsInSummary(inputControl)) { // New error string propertyName = null; object entity; BindingExpression be; ValidationMetadata vmd = ValidationHelper.ParseMetadata(inputControl, false, out entity, out be); if (vmd != null) { propertyName = vmd.Caption; } ValidationSummaryItem vsi = new ValidationSummaryItem(message, propertyName, ValidationSummaryItemType.PropertyError, new ValidationSummaryItemSource(propertyName, inputControl as Control), null); this._errors.Add(vsi); this._validationSummaryItemDictionary[key] = vsi; } } } }
/// <summary> /// Compare ValidationSummaryItems for display in the ValidationSummary /// </summary> /// <param name="x">The first reference used for comparison.</param> /// <param name="y">The second reference used for comparison.</param> /// <returns>The result of the comparison check between the two references.</returns> internal static int CompareValidationSummaryItems(ValidationSummaryItem x, ValidationSummaryItem y) { int returnVal; if (!ReferencesAreValid(x, y, out returnVal)) { // Do a null comparison check if one (or both) are null return(returnVal); } // Compare ErrorSource if (TryCompareReferences(x.ItemType, y.ItemType, out returnVal)) { return(returnVal); } // Compare Control Control controlX = x.Sources.Count > 0 ? x.Sources[0].Control : null; Control controlY = y.Sources.Count > 0 ? y.Sources[0].Control : null; if (controlX != controlY) { if (!ReferencesAreValid(controlX, controlY, out returnVal)) { // Do a null comparison check if one is null return(returnVal); } // Both are controls if (controlX.TabIndex != controlY.TabIndex) { // Sort by TabIndex return(controlX.TabIndex.CompareTo(controlY.TabIndex)); } // Both share the same parent, sort by index returnVal = SortByVisualTreeOrdering(controlX, controlY); if (returnVal != 0) { return(returnVal); } // TabIndexes and ordering are the same, move to next check if (TryCompareReferences(controlX.Name, controlY.Name, out returnVal)) { return(returnVal); } } // If we reached this point, we could not compare by Control, TabIndex, nor Name. // Compare by MessageHeader if (TryCompareReferences(x.MessageHeader, y.MessageHeader, out returnVal)) { return(returnVal); } // Compare by ErrorMessage TryCompareReferences(x.Message, y.Message, out returnVal); return(returnVal); }
/// <summary> /// Function to publish message to the message panel. /// </summary> /// <param name="msg"></param> public void PublishMessage(XElement msg) { string severity = string.Empty; if (msg.Attribute(Common.MessageType) != null) severity = msg.Attribute(Common.MessageType).Value.ToUpper(); string message = msg.Value; ValidationSummaryItem item = new ValidationSummaryItem(msg.Value); //TextBlock MSG = new TextBlock(); //MSG.Text = message; //if (severity == "ERROR") //{ // MSG.Foreground = new SolidColorBrush(Colors.Red); //} //else if (severity == "WARNING") //{ // MSG.Foreground = new SolidColorBrush(Colors.Black); //} //else //{ // MSG.Foreground = new SolidColorBrush(Colors.Green); //} if (msg.Attribute(Common.PopupMessage) != null && Common.boolValue(msg.Attribute(Common.PopupMessage).Value)) ApplicationEx.Instance.DisplayMessageBox(message, severity); this.Errors.Add(item); }
private void ExecuteClick(object sender) { ListBox lb = sender as ListBox; if (lb != null) { ValidationSummaryItem vsi = lb.SelectedItem as ValidationSummaryItem; if (vsi != null && this.FocusControlsOnClick) { int idx; // Ensure the currently selected item source is valid if (vsi.Sources.Count == 0) { // Clear the current ESI source if the ESI has none, such as when the ESI has changed this._currentValidationSummaryItemSource = null; } else { // If the current ESI source is not part of the current set, select the first one by default. idx = FindMatchingErrorSource(vsi.Sources, this._currentValidationSummaryItemSource); if (idx < 0) { this._currentValidationSummaryItemSource = vsi.Sources[0]; } } // Raise the event FocusingInvalidControlEventArgs e = new FocusingInvalidControlEventArgs(vsi, this._currentValidationSummaryItemSource); this.OnFocusingInvalidControl(e); // Raise the AutomationPeer event ValidationSummaryAutomationPeer peer = ValidationSummaryAutomationPeer.FromElement(this) as ValidationSummaryAutomationPeer; if (peer != null && AutomationPeer.ListenerExists(AutomationEvents.InvokePatternOnInvoked)) { peer.RaiseAutomationEvent(AutomationEvents.InvokePatternOnInvoked); } // Focus the target, which will usually be the current ESI source or the overwritten one if (!e.Handled && e.Target != null && e.Target.Control != null) { e.Target.Control.Focus(); } // Update currently selected item, but only if there are multiple ESI sources. if (vsi.Sources.Count > 0) { idx = FindMatchingErrorSource(vsi.Sources, e.Target); idx = idx < 0 ? 0 : ++idx % vsi.Sources.Count; this._currentValidationSummaryItemSource = vsi.Sources[idx]; } } } }
/// <summary> /// Validates the current item. /// </summary> /// <param name="validateAllProperties">Whether or not to validate all properties.</param> /// <returns>Whether or not the current item is valid.</returns> private bool ValidateItem(bool validateAllProperties) { CancelEventArgs e = new CancelEventArgs(); this.OnValidatingItem(e); if (e.Cancel) { return this.IsItemValid; } // Clear entity errors both from the ErrorSummary and the entity errors list. this.ClearEntityErrors(); if (validateAllProperties) { // Check all input controls and validate them. this.UpdateAllSources(); } if (this._lastItem != null) { // Check the rest of the parameters on the entity object. ValidationContext context = new ValidationContext(this._lastItem, null, null); List<ValidationResult> validationResults = new List<ValidationResult>(); bool valid = Validator.TryValidateObject(this._lastItem, context, validationResults, validateAllProperties); if (!valid) { Debug.Assert(validationResults.Count > 0, "Entity is not valid, but there are no errors."); foreach (ValidationResult result in validationResults) { string errorMessage = result.ErrorMessage; ValidationSummaryItem newError = new ValidationSummaryItem(errorMessage, null, ValidationSummaryItemType.ObjectError, null, null); // Indicate that this DataForm is the owner of the error. When clearing errors, only errors from this DataForm should be cleared. newError.Context = this; foreach (string property in result.MemberNames) { // Find a control matching this property name. Control c = null; if (this._templateBindingInfos != null) { foreach (DataFormBindingInfo bindingInfo in this._templateBindingInfos) { if (bindingInfo.BindingExpression != null && bindingInfo.BindingExpression.ParentBinding != null && bindingInfo.BindingExpression.ParentBinding.Path.Path == property) { c = bindingInfo.Element as Control; break; } } } ValidationSummaryItemSource errorSource = new ValidationSummaryItemSource(property, c); newError.Sources.Add(errorSource); } // Only add the errors that weren't picked up from the field-level validation. if (this.EntityErrorShouldBeAdded(newError)) { this._entityLevelErrors.Add(newError); if (this.ValidationSummary != null) { Debug.Assert(this.ValidationSummary.Errors != null, "ValidationSummary.Errors should never be null."); if (!this.ValidationSummary.Errors.Contains(newError)) { this.ValidationSummary.Errors.Add(newError); } } } } this.SetIsItemValid(); return false; } validationResults.Clear(); } this.SetIsItemValid(); return this.IsItemValid; }
/// <summary> /// Returns whether or not a new error should be added to the list of errors. /// </summary> /// <param name="newError">The new error.</param> /// <returns>Whether or not the new error should be added to the list of errors.</returns> private bool EntityErrorShouldBeAdded(ValidationSummaryItem newError) { if (this.ValidationSummary != null) { foreach (ValidationSummaryItem item in this.ValidationSummary.Errors) { if (item.ItemType == ValidationSummaryItemType.PropertyError && item.Sources != null) { foreach (ValidationSummaryItemSource source in item.Sources) { foreach (ValidationSummaryItemSource newErrorSource in newError.Sources) { if (newErrorSource.Control == source.Control) { return false; } } } } } } return true; }
/// <summary> /// Handles the ValidationSummary's SelectionChanged event and changes which cells are displayed as invalid. /// </summary> /// <param name="sender">ValidationSummary</param> /// <param name="e">SelectionChangedEventArgs</param> private void ValidationSummary_SelectionChanged(object sender, SelectionChangedEventArgs e) { // ValidationSummary only supports single-selection mode. if (e.AddedItems.Count == 1) { this._selectedValidationSummaryItem = e.AddedItems[0] as ValidationSummaryItem; } this.UpdateValidationStatus(); }
/// <summary> /// Create an ValidationSummaryItem for a given ValidationResult, by finding all cells related to the /// validation error and adding them as separate ValidationSummaryItemSources. /// </summary> /// <param name="validationResult">ValidationResult</param> /// <returns>ValidationSummaryItem</returns> private ValidationSummaryItem CreateValidationSummaryItem(ValidationResult validationResult) { Debug.Assert(validationResult != null); Debug.Assert(this._validationSummary != null); Debug.Assert(this.EditingRow != null); ValidationSummaryItem validationSummaryItem = new ValidationSummaryItem(validationResult.ErrorMessage); validationSummaryItem.Context = validationResult; string messageHeader = null; foreach (DataGridColumn column in this.ColumnsInternal.GetDisplayedColumns(c => c.IsVisible && !c.IsReadOnly)) { foreach (string property in validationResult.MemberNames) { if (!string.IsNullOrEmpty(property) && column.BindingPaths.Contains(property)) { validationSummaryItem.Sources.Add(new ValidationSummaryItemSource(property, this.EditingRow.Cells[column.Index])); if (string.IsNullOrEmpty(messageHeader) && column.Header != null) { messageHeader = column.Header.ToString(); } } } } Debug.Assert(validationSummaryItem.ItemType == ValidationSummaryItemType.ObjectError); if (this._propertyValidationResults.ContainsEqualValidationResult(validationResult)) { validationSummaryItem.MessageHeader = messageHeader; validationSummaryItem.ItemType = ValidationSummaryItemType.PropertyError; } return validationSummaryItem; }
/// <summary> /// Handles the ValidationSummary's SelectionChanged event and changes which cells are displayed as invalid. /// </summary> /// <param name="sender">ValidationSummary</param> /// <param name="e">SelectionChangedEventArgs</param> private void ValidationSummary_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (this.EditingRow != null) { // Reset all of the cells to valid foreach (DataGridCell cell in this.EditingRow.Cells) { cell.IsValid = true; } // ValidationSummary only supports single-selection mode. Set all cells related to the // selected error as invalid. if (e.AddedItems.Count > 0) { this._selectedValidationSummaryItem = e.AddedItems[0] as ValidationSummaryItem; if (this._selectedValidationSummaryItem != null) { foreach (ValidationSummaryItemSource source in this._selectedValidationSummaryItem.Sources) { DataGridCell cell = source.Control as DataGridCell; if (cell != null) { cell.IsValid = false; } } } } else { this._selectedValidationSummaryItem = null; } // Update the cell validation visuals foreach (DataGridCell cell in this.EditingRow.Cells) { cell.ApplyCellState(true); } } }
/// <summary> /// Create an ValidationSummaryItem for a given ValidationResult, by finding all cells related to the /// validation error and adding them as separate ValidationSummaryItemSources. /// </summary> /// <param name="validationResult">ValidationResult</param> /// <returns>ValidationSummaryItem</returns> private ValidationSummaryItem CreateValidationSummaryItem(ValidationResult validationResult) { Debug.Assert(validationResult != null); Debug.Assert(this._validationSummary != null); Debug.Assert(this.EditingRow != null); ValidationSummaryItem validationSummaryItem = new ValidationSummaryItem(validationResult.ErrorMessage); validationSummaryItem.Context = validationResult; foreach (DataGridColumn column in this.ColumnsInternal.GetDisplayedColumns(c => c.Visibility == Visibility.Visible && !c.IsReadOnly)) { foreach (string property in validationResult.MemberNames) { if (!string.IsNullOrEmpty(property) && column.BindingPaths.Contains(property)) { validationSummaryItem.Sources.Add(new ValidationSummaryItemSource(property, this.EditingRow.Cells[column.Index])); } } } return validationSummaryItem; }
private void Target_BindingValidationError(object sender, ValidationErrorEventArgs e) { FrameworkElement inputControl = e.OriginalSource as FrameworkElement; if (e != null && e.Error != null && e.Error.Exception != null && inputControl != null) { string key = String.IsNullOrEmpty(inputControl.Name) ? inputControl.GetHashCode().ToString(CultureInfo.InvariantCulture) : inputControl.Name; key += e.Error.Exception.Message; if (this._validationSummaryItemDictionary.ContainsKey(key)) { ValidationSummaryItem existingError = this._validationSummaryItemDictionary[key]; this._errors.Remove(existingError); this._validationSummaryItemDictionary.Remove(key); } if (e.Action == ValidationErrorEventAction.Added) { if (GetShowErrorsInSummary(inputControl)) { // New error string propertyName = null; object entity; BindingExpression be; ValidationMetadata vmd = ValidationHelper.ParseMetadata(inputControl, false, out entity, out be); if (vmd != null) { propertyName = vmd.Caption; } ValidationSummaryItem vsi = new ValidationSummaryItem(e.Error.Exception.Message, propertyName, ValidationSummaryItemType.PropertyError, new ValidationSummaryItemSource(propertyName, inputControl as Control), null); this._errors.Add(vsi); this._validationSummaryItemDictionary[key] = vsi; } } } }
/// <summary> /// Compare ValidationSummaryItems for display in the ValidationSummary /// </summary> /// <param name="x">The first reference used for comparison.</param> /// <param name="y">The second reference used for comparison.</param> /// <returns>The result of the comparison check between the two references.</returns> internal static int CompareValidationSummaryItems(ValidationSummaryItem x, ValidationSummaryItem y) { int returnVal; if (!ReferencesAreValid(x, y, out returnVal)) { // Do a null comparison check if one (or both) are null return returnVal; } // Compare ErrorSource if (TryCompareReferences(x.ItemType, y.ItemType, out returnVal)) { return returnVal; } // Compare Control Control controlX = x.Sources.Count > 0 ? x.Sources[0].Control : null; Control controlY = y.Sources.Count > 0 ? y.Sources[0].Control : null; if (controlX != controlY) { if (!ReferencesAreValid(controlX, controlY, out returnVal)) { // Do a null comparison check if one is null return returnVal; } // Both are controls if (controlX.TabIndex != controlY.TabIndex) { // Sort by TabIndex return controlX.TabIndex.CompareTo(controlY.TabIndex); } // Both share the same parent, sort by index returnVal = SortByVisualTreeOrdering(controlX, controlY); if (returnVal != 0) { return returnVal; } // TabIndexes and ordering are the same, move to next check if (TryCompareReferences(controlX.Name, controlY.Name, out returnVal)) { return returnVal; } } // If we reached this point, we could not compare by Control, TabIndex, nor Name. // Compare by MessageHeader if (TryCompareReferences(x.MessageHeader, y.MessageHeader, out returnVal)) { return returnVal; } // Compare by ErrorMessage TryCompareReferences(x.Message, y.Message, out returnVal); return returnVal; }