Code:
/ DotNET / DotNET / 8.0 / untmp / WIN_WINDOWS / lh_tools_devdiv_wpf / Windows / wcp / Framework / System / Windows / Controls / validation.cs / 1 / validation.cs
//---------------------------------------------------------------------------- // //// Copyright (C) 2005 by Microsoft Corporation. All rights reserved. // // // // Description: // Validation-related methods and DependencyProperties // // See specs at [....]/connecteddata/Specs/Validation.mht // // History: // 02/03/2005 [....]: created. // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Media; using MS.Internal.Controls; using MS.Internal.Data; using MS.Internal.KnownBoxes; using MS.Utility; namespace System.Windows.Controls { ////// Validation-related methods and DependencyProperties /// public static class Validation { ////// ValidationError event /// public static readonly RoutedEvent ErrorEvent = EventManager.RegisterRoutedEvent("ValidationError", RoutingStrategy.Bubble, typeof(EventHandler), typeof(Validation)); /// /// Adds a handler for the ValidationError attached event /// /// UIElement or ContentElement that listens to this event /// Event Handler to be added public static void AddErrorHandler(DependencyObject element, EventHandlerhandler) { FrameworkElement.AddHandler(element, ErrorEvent, handler); } /// /// Removes a handler for the ValidationError attached event /// /// UIElement or ContentElement that listens to this event /// Event Handler to be removed public static void RemoveErrorHandler(DependencyObject element, EventHandlerhandler) { FrameworkElement.RemoveHandler(element, ErrorEvent, handler); } /// /// The key needed to set the publicly read-only ValidationErrors property. /// internal static readonly DependencyPropertyKey ErrorsPropertyKey = DependencyProperty.RegisterAttachedReadOnly("Errors", typeof(ReadOnlyObservableCollection), typeof(Validation), new FrameworkPropertyMetadata( ValidationErrorCollection.Empty, FrameworkPropertyMetadataOptions.NotDataBindable)); /// /// ValidationErrors DependencyProperty. /// holds the list of all active validation errors of any data binding targeting the hosting element. /// ////// The application cannot modify the content of this collection. /// public static readonly DependencyProperty ErrorsProperty = ErrorsPropertyKey.DependencyProperty; ///Static accessor for Validation.Errors property ////// The application cannot modify the content of this collection. /// ///DependencyObject element cannot be null public static ReadOnlyObservableCollectionGetErrors(DependencyObject element) { if (element == null) throw new ArgumentNullException("element"); return (ReadOnlyObservableCollection ) element.GetValue(ErrorsProperty); } /// /// holds the internally modifiable collection of validation errors. /// internal static readonly DependencyProperty ValidationErrorsInternalProperty = DependencyProperty.RegisterAttached("ErrorsInternal", typeof(ValidationErrorCollection), typeof(Validation), new FrameworkPropertyMetadata( (ValidationErrorCollection)null, new PropertyChangedCallback(OnErrorsInternalChanged))); // Update HasErrors and Invalidate the public ValidationErrors property whose GetOverride will return // the updated value of ValidationErrorsInternal, nicely wrapped into a ReadOnlyCollectionprivate static void OnErrorsInternalChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ValidationErrorCollection newErrors = e.NewValue as ValidationErrorCollection; if ((newErrors == null) || (newErrors.Count == 0)) { d.ClearValue(HasErrorPropertyKey); d.ClearValue(ErrorsPropertyKey); } else { d.SetValue(HasErrorPropertyKey, BooleanBoxes.TrueBox); d.SetValue(ErrorsPropertyKey, new ReadOnlyObservableCollection (newErrors)); } } internal static ValidationErrorCollection GetErrorsInternal(DependencyObject target) { return (ValidationErrorCollection) target.GetValue(Validation.ValidationErrorsInternalProperty); } /// /// The key needed set a read-only property. /// internal static readonly DependencyPropertyKey HasErrorPropertyKey = DependencyProperty.RegisterAttachedReadOnly("HasError", typeof(bool), typeof(Validation), new FrameworkPropertyMetadata( BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.NotDataBindable)); ////// HasError DependencyProperty is true if any binding on the target element /// has a validation error. /// public static readonly DependencyProperty HasErrorProperty= HasErrorPropertyKey.DependencyProperty; ///Static accessor for HasError property ///DependencyObject element cannot be null public static bool GetHasError(DependencyObject element) { if (element == null) throw new ArgumentNullException("element"); return (bool) element.GetValue(HasErrorProperty); } ////// Template used to generate validation error feedback on the AdornerLayer. Default /// Template is: /// public static readonly DependencyProperty ErrorTemplateProperty = DependencyProperty.RegisterAttached("ErrorTemplate", typeof(ControlTemplate), typeof(Validation), new FrameworkPropertyMetadata( CreateDefaultErrorTemplate(), FrameworkPropertyMetadataOptions.NotDataBindable)); //////
////// ////// Static accessor for ErrorTemplate property ///DependencyObject element cannot be null [AttachedPropertyBrowsableForType(typeof(DependencyObject))] public static ControlTemplate GetErrorTemplate(DependencyObject element) { if (element == null) throw new ArgumentNullException("element"); return element.GetValue(ErrorTemplateProperty) as ControlTemplate; } ///Static modifier for ErrorTemplate property ///DependencyObject element cannot be null public static void SetErrorTemplate(DependencyObject element, ControlTemplate value) { if (element == null) throw new ArgumentNullException("element"); // (perf) don't set if the existing value is already correct object oldValue = element.ReadLocalValue(ErrorTemplateProperty); if (!Object.Equals(oldValue, value)) element.SetValue(ErrorTemplateProperty, value); } internal static void ShowValidationAdorner(DependencyObject targetElement, bool show) { UIElement targetUIElement = targetElement as UIElement; if (targetUIElement != null) { AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(targetUIElement); if (adornerLayer == null) return; TemplatedAdorner validationAdorner = targetUIElement.ReadLocalValue(ValidationAdornerProperty) as TemplatedAdorner; if (show && validationAdorner == null) { ControlTemplate validationTemplate = GetErrorTemplate(targetUIElement); if (validationTemplate != null) { validationAdorner = new TemplatedAdorner(targetUIElement, validationTemplate); adornerLayer.Add(validationAdorner); targetUIElement.SetValue(ValidationAdornerProperty, validationAdorner); } } else if (!show && validationAdorner != null) { validationAdorner.ClearChild(); adornerLayer.Remove(validationAdorner); targetUIElement.ClearValue(ValidationAdornerProperty); } } } ////// 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. /// 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); } ////// Clears the ValidationError that was set through a call /// to MarkInvalid or a previously failed validation of that BindingExpression. /// public static void ClearInvalid(BindingExpressionBase bindingExpression) { if (bindingExpression == null) throw new ArgumentNullException("bindingExpression"); bindingExpression.UpdateValidationError(null); } private static ControlTemplate CreateDefaultErrorTemplate() { ControlTemplate defaultTemplate = new ControlTemplate(typeof(Control)); //// FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border), "Border"); border.SetValue(Border.BorderBrushProperty, Brushes.Red); border.SetValue(Border.BorderThicknessProperty, new Thickness(1)); FrameworkElementFactory adornedElementPlaceHolder = new FrameworkElementFactory(typeof(AdornedElementPlaceholder), "Placeholder"); border.AppendChild(adornedElementPlaceHolder); defaultTemplate.VisualTree = border; defaultTemplate.Seal(); return defaultTemplate; } ///// /// Reference to the ValidationAdorner /// private static readonly DependencyProperty ValidationAdornerProperty = DependencyProperty.RegisterAttached("ValidationAdorner", typeof(TemplatedAdorner), typeof(Validation), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.NotDataBindable)); } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. // Copyright (c) Microsoft Corporation. All rights reserved.
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- DocComment.cs
- TraceFilter.cs
- StringUtil.cs
- AggregateException.cs
- EntityProviderFactory.cs
- CircleHotSpot.cs
- DbExpressionVisitor_TResultType.cs
- DataServiceQueryOfT.cs
- ReadOnlyDictionary.cs
- ByteKeyFrameCollection.cs
- XmlWellformedWriter.cs
- ToolbarAUtomationPeer.cs
- _BaseOverlappedAsyncResult.cs
- EasingFunctionBase.cs
- FontDriver.cs
- SimpleHandlerFactory.cs
- PathSegment.cs
- ValuePatternIdentifiers.cs
- RectValueSerializer.cs
- DetailsViewDeleteEventArgs.cs
- CqlBlock.cs
- CodeStatementCollection.cs
- OleCmdHelper.cs
- SelectionPattern.cs
- FormViewPageEventArgs.cs
- mansign.cs
- XmlStreamNodeWriter.cs
- XmlNamespaceDeclarationsAttribute.cs
- LoginName.cs
- StreamHelper.cs
- ImageUrlEditor.cs
- Context.cs
- AssemblyAssociatedContentFileAttribute.cs
- SqlRetyper.cs
- MetadataUtilsSmi.cs
- ZipIOLocalFileHeader.cs
- SignatureHelper.cs
- TabPanel.cs
- BaseTemplateCodeDomTreeGenerator.cs
- CodeGroup.cs
- PropertyGridEditorPart.cs
- FrameworkElementFactoryMarkupObject.cs
- ResumeStoryboard.cs
- ListViewItem.cs
- GatewayIPAddressInformationCollection.cs
- InvalidAsynchronousStateException.cs
- DataGridViewButtonCell.cs
- CompleteWizardStep.cs
- DoubleStorage.cs
- CatalogPartChrome.cs
- HMACSHA384.cs
- LayoutInformation.cs
- PingReply.cs
- SystemWebSectionGroup.cs
- XmlAttributeProperties.cs
- X509Chain.cs
- WmlListAdapter.cs
- MemoryRecordBuffer.cs
- KeyEvent.cs
- InvokeWebService.cs
- AttributeAction.cs
- ObjectListDataBindEventArgs.cs
- XmlEncodedRawTextWriter.cs
- DiscriminatorMap.cs
- VirtualDirectoryMappingCollection.cs
- HttpStreamMessageEncoderFactory.cs
- StorageTypeMapping.cs
- PassportIdentity.cs
- FrameDimension.cs
- X509WindowsSecurityToken.cs
- ReaderWriterLockWrapper.cs
- _ConnectStream.cs
- CodeConditionStatement.cs
- DataServiceCollectionOfT.cs
- HttpCapabilitiesBase.cs
- ToolStripPanelRenderEventArgs.cs
- ProcessHostConfigUtils.cs
- ComplexTypeEmitter.cs
- DbParameterCollectionHelper.cs
- BackgroundFormatInfo.cs
- AuthenticateEventArgs.cs
- GeneralTransform.cs
- InstanceContext.cs
- ToolZone.cs
- InfoCardRSAPKCS1SignatureDeformatter.cs
- SiteMapNode.cs
- IgnoreFileBuildProvider.cs
- OleDbConnection.cs
- LinkedResourceCollection.cs
- XmlSchemaObjectTable.cs
- SupportsPreviewControlAttribute.cs
- BitmapCacheBrush.cs
- IntPtr.cs
- TargetParameterCountException.cs
- EdmError.cs
- HtmlTableCell.cs
- ShapingWorkspace.cs
- SymbolTable.cs
- TypeDescriptionProvider.cs
- PhysicalAddress.cs