예제 #1
0
        // Token: 0x06003E37 RID: 15927 RVA: 0x0011D778 File Offset: 0x0011B978
        internal static PropertyRecord[] GetPropertyRecordArray(DependencyObject d)
        {
            LocalValueEnumerator localValueEnumerator = d.GetLocalValueEnumerator();

            PropertyRecord[] array = new PropertyRecord[localValueEnumerator.Count];
            int num = 0;

            localValueEnumerator.Reset();
            while (localValueEnumerator.MoveNext())
            {
                LocalValueEntry    localValueEntry = localValueEnumerator.Current;
                DependencyProperty property        = localValueEntry.Property;
                if (!property.ReadOnly)
                {
                    array[num].Property = property;
                    array[num].Value    = d.GetValue(property);
                    num++;
                }
            }
            PropertyRecord[] array2;
            if (localValueEnumerator.Count != num)
            {
                array2 = new PropertyRecord[num];
                for (int i = 0; i < num; i++)
                {
                    array2[i] = array[i];
                }
            }
            else
            {
                array2 = array;
            }
            return(array2);
        }
예제 #2
0
        /// <summary>
        /// Valida todos los controles de una ventana que se pase por parametro. Si existe algún error de validación se remarca
        /// </summary>
        /// <param name="parent"></param>
        /// <returns></returns>
        public static bool EsValido(DependencyObject parent)
        {
            bool valido = true;
            LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;
                if (BindingOperations.IsDataBound(parent, entry.Property))
                {
                    Binding binding = BindingOperations.GetBinding(parent, entry.Property);
                    foreach (ValidationRule reglaValidacion in binding.ValidationRules)
                    {
                        ValidationResult result = reglaValidacion.Validate(parent.GetValue(entry.Property), null);
                        if (!result.IsValid)
                        {
                            BindingExpression expresion = BindingOperations.GetBindingExpression(parent, entry.Property);
                            System.Windows.Controls.Validation.MarkInvalid(expresion, new ValidationError(reglaValidacion, expresion, result.ErrorContent, null));
                            valido = false;
                        }
                    }
                }
            }
            for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                if (!EsValido(child))
                {
                    valido = false;
                }
            }
            return(valido);
        }
예제 #3
0
        public static bool IsParentValid(DependencyObject parent)
        {
            bool valid = true;
            LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;
                if (BindingOperations.IsDataBound(parent, entry.Property))
                {
                    Binding binding = BindingOperations.GetBinding(parent, entry.Property);
                    if (binding.ValidationRules.Count > 0)
                    {
                        BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);
                        expression.UpdateSource();

                        if (expression.HasError)
                        {
                            valid = false;
                        }
                    }
                }
            }
            return(valid);
        }
예제 #4
0
        /// <summary>
        /// Recorre todas las validaciones cargadas en el pariente para desactivarlas
        /// </summary>
        /// <param name="parent"></param>
        public static void LimpiarValidaciones(DependencyObject parent)
        {
            LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;
                if (BindingOperations.IsDataBound(parent, entry.Property))
                {
                    Binding binding = BindingOperations.GetBinding(parent, entry.Property);
                    foreach (ValidationRule reglaValidacion in binding.ValidationRules)
                    {
                        ValidationResult result = reglaValidacion.Validate(parent.GetValue(entry.Property), null);
                        if (!result.IsValid)
                        {
                            BindingExpression expresion = BindingOperations.GetBindingExpression(parent, entry.Property);
                            System.Windows.Controls.Validation.ClearInvalid(expresion);
                        }
                    }
                }
            }
            for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                LimpiarValidaciones(child);
            }
        }
        private static void Clone(DependencyObject from, DependencyObject to)
        {
            LocalValueEnumerator localValueEnumerator = from.GetLocalValueEnumerator();

            while (localValueEnumerator.MoveNext())
            {
                LocalValueEntry current = localValueEnumerator.Current;
                if (!current.Property.ReadOnly)
                {
                    current = localValueEnumerator.Current;
                    if (!(current.Value is FrameworkElement))
                    {
                        current = localValueEnumerator.Current;
                        if (!(current.Value is BindingExpressionBase))
                        {
                            DependencyObject dependencyObject = to;
                            current = localValueEnumerator.Current;
                            DependencyProperty property = current.Property;
                            current = localValueEnumerator.Current;
                            object obj = current.Value;
                            try
                            {
                                dependencyObject.SetCurrentValue(property, obj);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }
        }
예제 #6
0
        /// <summary>
        /// Remove all data Binding (if any) from a DependencyObject.
        /// </summary>
        /// <param name="target">object from which to remove bindings</param>
        /// <exception cref="ArgumentNullException"> DependencyObject target cannot be null </exception>
        public static void ClearAllBindings(DependencyObject target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }
//            target.VerifyAccess();

            LocalValueEnumerator lve = target.GetLocalValueEnumerator();

            // Batch properties that have BindingExpressions since clearing
            // during a local value enumeration is illegal
            ArrayList batch = new ArrayList(8);

            while (lve.MoveNext())
            {
                LocalValueEntry entry = lve.Current;
                if (IsDataBound(target, entry.Property))
                {
                    batch.Add(entry.Property);
                }
            }

            // Clear all properties that are storing BindingExpressions
            for (int i = 0; i < batch.Count; i++)
            {
                target.ClearValue((DependencyProperty)batch[i]);
            }
        }
예제 #7
0
        private void GenerateBehaviorActions(ActionCollection actionCollection, CodeTypeDeclaration classType, CodeMemberMethod method, CodeVariableReferenceExpression behaviorVarRef, string behaviorName)
        {
            for (int i = 0; i < actionCollection.Count; i++)
            {
                var    action     = actionCollection[i];
                string actionName = behaviorName + "_ACT_" + i;
                Type   type       = action.GetType();

                CodeVariableDeclarationStatement variable = new CodeVariableDeclarationStatement(type.Name, actionName, new CodeObjectCreateExpression(type.Name));
                method.Statements.Add(variable);
                var actionVarRef = new CodeVariableReferenceExpression(actionName);

                method.Statements.Add(new CodeMethodInvokeExpression(
                                          behaviorVarRef, "Actions.Add", actionVarRef));

                ValueGenerator valueGenerator      = new ValueGenerator();
                MethodInfo     generateFieldMethod = typeof(CodeComHelper).GetMethod("GenerateField");

                LocalValueEnumerator enumerator = action.GetLocalValueEnumerator();
                while (enumerator.MoveNext())
                {
                    LocalValueEntry    entry    = enumerator.Current;
                    DependencyProperty property = entry.Property;
                    Type valueType = entry.Value.GetType();
                    if (CodeComHelper.IsValidForFieldGenerator(entry.Value))
                    {
                        if (valueGenerator.Generators.ContainsKey(property.PropertyType) || valueGenerator.Generators.ContainsKey(valueType))
                        {
                            CodeExpression propValue = valueGenerator.ProcessGenerators(classType, method, entry.Value, actionName);
                            if (propValue != null)
                            {
                                method.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(actionVarRef, property.Name), propValue));
                            }
                        }
                        else if (entry.Value is PropertyPath)
                        {
                            PropertyPath path = entry.Value as PropertyPath;
                            method.Statements.Add(new CodeAssignStatement(
                                                      new CodeFieldReferenceExpression(actionVarRef, property.Name),
                                                      new CodeObjectCreateExpression("PropertyPath", new CodePrimitiveExpression(path.Path))));
                        }
                        else
                        {
                            MethodInfo generic = generateFieldMethod.MakeGenericMethod(property.PropertyType);
                            if (generic == null)
                            {
                                throw new NullReferenceException("Generic method not created for type - " + property.PropertyType);
                            }

                            generic.Invoke(null, new object[] { method, actionVarRef, action, property });
                        }
                    }
                }

                CodeComHelper.GenerateBindings(method, actionVarRef, action, actionName, behaviorVarRef);
                //CodeComHelper.GenerateResourceReferences(method, actionVarRef, action);
            }
        }
        public static void CopyLocalValuesTo <T>(this T sourceObject, T destinationObject) where T : DependencyObject
        {
            LocalValueEnumerator localValueEnumerator = sourceObject.GetLocalValueEnumerator();

            while (localValueEnumerator.MoveNext())
            {
                LocalValueEntry current = localValueEnumerator.Current;
                destinationObject.SetValue(current.Property, current.Value);
            }
        }
예제 #9
0
        public DependencyObject FindBoundElement(String fullPath, DependencyObject parent, out String PropertyOriginal)
        {
            DependencyObject boundElement = null;

            PropertyOriginal = null;

            LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;
                if (BindingOperations.IsDataBound(parent, entry.Property))
                {
                    BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);
                    //Binding binding = BindingOperations.GetBinding(parent, entry.Property);

                    if (expression == null)
                    {
                        continue;
                    }
                    try
                    {
                        //VNEmpresa.WriteLine(entry.Property.Name + ", " + expression.ParentBinding.Path.Path);
                    }
                    catch (Exception)
                    {
                    }

                    if (String.Equals(expression.ParentBinding.Path?.Path, fullPath, StringComparison.OrdinalIgnoreCase))
                    {
                        PropertyOriginal = expression.TargetProperty.Name;
                        return(parent);
                    }
                }
            }

            if (boundElement != null)
            {
                return(boundElement);
            }

            // Iterate through all children
            for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)
            {
                DependencyObject child  = VisualTreeHelper.GetChild(parent, i);
                DependencyObject result = FindBoundElement(fullPath, child, out PropertyOriginal);
                if (result != null)
                {
                    boundElement = result;
                    return(boundElement);
                }
            }

            return(boundElement);
        }
예제 #10
0
        private void GenerateBehaviors(BehaviorCollection behaviors, CodeTypeDeclaration classType, CodeMemberMethod method, FrameworkElement element, CodeExpression fieldReference)
        {
            for (int i = 0; i < behaviors.Count; i++)
            {
                var    behavior     = behaviors[i];
                string behaviorName = element.Name + "_BEH_" + i;
                Type   type         = behavior.GetType();
                CodeVariableDeclarationStatement variable = new CodeVariableDeclarationStatement(type.Name, behaviorName, new CodeObjectCreateExpression(type.Name));
                method.Statements.Add(variable);
                var behaviorVarRef = new CodeVariableReferenceExpression(behaviorName);

                method.Statements.Add(new CodeMethodInvokeExpression(
                                          new CodeVariableReferenceExpression("Interaction"), "GetBehaviors(" + element.Name + ").Add", behaviorVarRef));

                ValueGenerator valueGenerator      = new ValueGenerator();
                MethodInfo     generateFieldMethod = typeof(CodeComHelper).GetMethod("GenerateField");

                LocalValueEnumerator enumerator = behavior.GetLocalValueEnumerator();
                while (enumerator.MoveNext())
                {
                    LocalValueEntry    entry    = enumerator.Current;
                    DependencyProperty property = entry.Property;
                    Type valueType = entry.Value.GetType();
                    if (CodeComHelper.IsValidForFieldGenerator(entry.Value))
                    {
                        if (valueGenerator.Generators.ContainsKey(property.PropertyType) || valueGenerator.Generators.ContainsKey(valueType))
                        {
                            CodeExpression propValue = valueGenerator.ProcessGenerators(classType, method, entry.Value, behaviorName);
                            if (propValue != null)
                            {
                                method.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(behaviorVarRef, property.Name), propValue));
                            }
                        }
                        else if (entry.Value is ActionCollection)
                        {
                            GenerateBehaviorActions(entry.Value as ActionCollection, classType, method, behaviorVarRef, behaviorName);
                        }
                        else
                        {
                            MethodInfo generic = generateFieldMethod.MakeGenericMethod(property.PropertyType);
                            if (generic == null)
                            {
                                throw new NullReferenceException("Generic method not created for type - " + property.PropertyType);
                            }

                            generic.Invoke(null, new object[] { method, behaviorVarRef, behavior, property });
                        }
                    }
                }

                CodeComHelper.GenerateBindings(method, behaviorVarRef, behavior, behaviorName);
                CodeComHelper.GenerateResourceReferences(method, behaviorVarRef, behavior);
            }
        }
        private void EnumerateBindings(DependencyObject target, Func <DependencyProperty, bool> action)
        {
            LocalValueEnumerator lve = target.GetLocalValueEnumerator();

            while (lve.MoveNext())
            {
                LocalValueEntry entry = lve.Current;

                if (BindingOperations.IsDataBound(target, entry.Property))
                {
                    action(entry.Property);
                }
            }
        }
예제 #12
0
 public static IEnumerable EnumerateDataBoundDependencyProperties(this DependencyObject obj)
 {
     if (obj != null)
     {
         LocalValueEnumerator enumerator = obj.GetLocalValueEnumerator();
         while (enumerator.MoveNext())
         {
             LocalValueEntry entry = enumerator.Current;
             if (BindingOperations.IsDataBound(obj, entry.Property))
             {
                 yield return(entry.Property);
             }
         }
     }
 }
        // Token: 0x06003D11 RID: 15633 RVA: 0x0011B9F4 File Offset: 0x00119BF4
        private static TableColumn CopyColumn(TableColumn sourceTableColumn)
        {
            TableColumn          tableColumn          = new TableColumn();
            LocalValueEnumerator localValueEnumerator = sourceTableColumn.GetLocalValueEnumerator();

            while (localValueEnumerator.MoveNext())
            {
                LocalValueEntry localValueEntry = localValueEnumerator.Current;
                if (!localValueEntry.Property.ReadOnly)
                {
                    tableColumn.SetValue(localValueEntry.Property, localValueEntry.Value);
                }
            }
            return(tableColumn);
        }
        private static TableColumn CopyColumn(TableColumn sourceTableColumn)
        {
            TableColumn          newTableColumn = new TableColumn();
            LocalValueEnumerator properties     = sourceTableColumn.GetLocalValueEnumerator();

            while (properties.MoveNext())
            {
                LocalValueEntry propertyEntry = properties.Current;
                if (!propertyEntry.Property.ReadOnly)
                {
                    newTableColumn.SetValue(propertyEntry.Property, propertyEntry.Value);
                }
            }

            return(newTableColumn);
        }
        private static void checkErrors(DependencyObject parent)
        {
            LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;
                if (BindingOperations.IsDataBound(parent, entry.Property))
                {
                    BindingExpression binding =
                        BindingOperations.GetBindingExpression(parent, entry.Property);

                    if (binding == null || // Not possible because of IsDataBound() check, but we leave it here to remove the warning
                        binding.DataItem == null)
                    {
                        continue;
                    }

                    if (binding.Status == BindingStatus.PathError)
                    {
                        var element = parent as FrameworkElement;
                        if (element != null)
                        {
                            var elementAdornerLayer = AdornerLayer.GetAdornerLayer(element);
                            if (elementAdornerLayer == null)
                            {
                                continue;
                            }

                            Adorner[] adorners = elementAdornerLayer.GetAdorners(element);
                            if (adorners != null)
                            {
                                foreach (Adorner a in adorners)
                                {
                                    if (a is BindingErrorBorderAdorner)
                                    {
                                        continue;
                                    }
                                }
                            }

                            elementAdornerLayer.Add(new BindingErrorBorderAdorner(element));
                        }
                    }
                }
            }
        }
        private static void UpdateBindings(DependencyObject obj)
        {
            LocalValueEnumerator lve = obj.GetLocalValueEnumerator();

            while (lve.MoveNext())
            {
                LocalValueEntry entry = lve.Current;

                if (BindingOperations.IsDataBound(obj, entry.Property))
                {
                    (entry.Value as BindingExpression).UpdateTarget();
                }
            }
            if (obj is ContentControl contentControl && contentControl.Content is DependencyObject dependencyObject)
            {
                UpdateBindings(dependencyObject);
            }
        }
예제 #17
0
        private static IEnumerable <BindingExpression> EnumerateBindings(DependencyObject element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            LocalValueEnumerator lve = element.GetLocalValueEnumerator();

            while (lve.MoveNext())
            {
                LocalValueEntry entry = lve.Current;

                if (BindingOperations.IsDataBound(element, entry.Property))
                {
                    yield return(((FrameworkElement)element).GetBindingExpression(entry.Property));
                    //yield return entry.Value as BindingExpression;
                }
            }
        }
예제 #18
0
        public static IEnumerable <Binding> EnumerateBindings(DependencyObject element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            LocalValueEnumerator lve = element.GetLocalValueEnumerator();

            while (lve.MoveNext())
            {
                LocalValueEntry entry = lve.Current;

                if (BindingOperations.IsDataBound(element, entry.Property))
                {
                    Binding binding = (entry.Value as BindingExpression).ParentBinding;
                    yield return(binding);
                }
            }
        }
        public static bool CheckAllValidationErrors(DependencyObject dependencyObject)
        {
            bool isValid = true;

            // The local values do not work with DataTemplates (but should show attached properties)...
            LocalValueEnumerator localValues = dependencyObject.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;
                isValid = CheckAllValidationErrors(dependencyObject, entry.Property);
            }

            //...we introspect the type using reflection to figure-out additional DPs that did not surface through the local values.
            foreach (DependencyProperty dependencyProperty in GetDependencyProperties(dependencyObject.GetType()))
            {
                isValid = CheckAllValidationErrors(dependencyObject, dependencyProperty);
            }

            return(isValid);
        }
예제 #20
0
        public static bool IsValid(DependencyObject parent)
        {
            // Validate all the bindings on the parent
            bool valid = true;
            LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;
                if (BindingOperations.IsDataBound(parent, entry.Property))
                {
                    Binding binding = BindingOperations.GetBinding(parent, entry.Property);
                    if (binding.ValidationRules.Count > 0)
                    {
                        BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);
                        expression.UpdateSource();

                        if (expression.HasError)
                        {
                            valid = false;
                        }
                    }
                }
            }

            // Validate all the bindings on the children
            System.Collections.IEnumerable children = LogicalTreeHelper.GetChildren(parent);
            foreach (object obj in children)
            {
                if (obj is DependencyObject)
                {
                    DependencyObject child = (DependencyObject)obj;
                    if (!IsValid(child))
                    {
                        valid = false;
                    }
                }
            }
            return(valid);
        }
예제 #21
0
        public static bool IsValid(DependencyObject obj)
        {
            // Validate all the bindings on the parent
            LocalValueEnumerator localValues = obj.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;
                if (BindingOperations.IsDataBound(obj, entry.Property))
                {
                    Binding binding = BindingOperations.GetBinding(obj, entry.Property);
                    if (binding.ValidationRules.Count > 0)
                    {
                        BindingExpression expression = BindingOperations.GetBindingExpression(obj, entry.Property);
                        expression.UpdateSource();

                        if (expression.HasError)
                        {
                            return(false); //early exit
                        }
                    }
                }
            }

            // Validate all the bindings on the children
            IEnumerable children = LogicalTreeHelper.GetChildren(obj);

            foreach (object child in children)
            {
                if (child is DependencyObject)
                {
                    if (!IsValid((DependencyObject)child))
                    {
                        return(false); //early exit
                    }
                }
            }

            return(true);
        }
		private ArrayList SaveSubStreams(UIElement element)
		{
			ArrayList arrayList = null;
			if (element != null && element.PersistId != 0)
			{
				LocalValueEnumerator localValueEnumerator = element.GetLocalValueEnumerator();
				while (localValueEnumerator.MoveNext())
				{
					LocalValueEntry localValueEntry = localValueEnumerator.Current;
					FrameworkPropertyMetadata frameworkPropertyMetadata = localValueEntry.Property.GetMetadata(element.DependencyObjectType) as FrameworkPropertyMetadata;
					if (frameworkPropertyMetadata != null && frameworkPropertyMetadata.Journal && !(localValueEntry.Value is Expression) && localValueEntry.Property != Frame.SourceProperty)
					{
						if (arrayList == null)
						{
							arrayList = new ArrayList(3);
						}
						object value = element.GetValue(localValueEntry.Property);
						byte[] dataBytes = null;
						if (value != null && !(value is Uri))
						{
							MemoryStream memoryStream = new MemoryStream();
							new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).Assert();
							try
							{
								this.Formatter.Serialize(memoryStream, value);
							}
							finally
							{
								CodeAccessPermission.RevertAssert();
							}
							dataBytes = memoryStream.ToArray();
							((IDisposable)memoryStream).Dispose();
						}
						arrayList.Add(new SubStream(localValueEntry.Property.Name, dataBytes));
					}
				}
			}
			return arrayList;
		}
        /// <summary>Removes all bindings, including bindings of type <see cref="T:System.Windows.Data.Binding" />, <see cref="T:System.Windows.Data.MultiBinding" />, and <see cref="T:System.Windows.Data.PriorityBinding" />, from the specified <see cref="T:System.Windows.DependencyObject" />.</summary>
        /// <param name="target">The object from which to remove bindings.</param>
        /// <exception cref="T:System.ArgumentNullException">If <paramref name="target" /> is <see langword="null" />.</exception>
        // Token: 0x06001A34 RID: 6708 RVA: 0x0007D1DC File Offset: 0x0007B3DC
        public static void ClearAllBindings(DependencyObject target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }
            LocalValueEnumerator localValueEnumerator = target.GetLocalValueEnumerator();
            ArrayList            arrayList            = new ArrayList(8);

            while (localValueEnumerator.MoveNext())
            {
                LocalValueEntry localValueEntry = localValueEnumerator.Current;
                if (BindingOperations.IsDataBound(target, localValueEntry.Property))
                {
                    arrayList.Add(localValueEntry.Property);
                }
            }
            for (int i = 0; i < arrayList.Count; i++)
            {
                target.ClearValue((DependencyProperty)arrayList[i]);
            }
        }
예제 #24
0
        // This is here 'til future versions of WPF provide this functionality
        public static bool ValidateBindings(DependencyObject parent)
        {
            // Validate all the bindings on the parent
            bool valid = true;
            LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;
                if (BindingOperations.IsDataBound(parent, entry.Property))
                {
                    Binding binding = BindingOperations.GetBinding(parent, entry.Property);
                    foreach (ValidationRule rule in binding.ValidationRules)
                    {
                        // TODO: where to get correct culture info?
                        ValidationResult result = rule.Validate(parent.GetValue(entry.Property), null);
                        if (!result.IsValid)
                        {
                            BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);
                            Validation.MarkInvalid(expression, new ValidationError(rule, expression, result.ErrorContent, null));
                            valid = false;
                        }
                    }
                }
            }

            // Validate all the bindings on the children
            for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                if (!ValidateBindings(child))
                {
                    valid = false;
                }
            }

            return(valid);
        }
예제 #25
0
        /// <summary>
        /// Proceed to validation of an object and make errors apparent
        /// </summary>
        /// <param name="parent"></param>
        internal static bool ValidateAllChildren(DependencyObject parent)
        {
            // Validate all the bindings on the parent
            //Debug.WriteLine("Validating {0} " , parent);
            bool valid = true;
            LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();

            while (localValues.MoveNext())
            {
                LocalValueEntry entry = localValues.Current;
                if (BindingOperations.IsDataBound(parent, entry.Property))
                {
                    Binding binding = BindingOperations.GetBinding(parent, entry.Property);
                    foreach (ValidationRule rule in binding.ValidationRules)
                    {
                        ValidationResult result = rule.Validate(parent.GetValue(entry.Property), null);
                        if (!result.IsValid)
                        {
                            BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);
                            System.Windows.Controls.Validation.MarkInvalid(expression, new ValidationError(rule, expression, result.ErrorContent, null));
                            valid = false;
                        }
                    }
                }
            }
            // Validate all the bindings on the children
            for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                if (!ValidateAllChildren(child))
                {
                    valid = false;
                }
            }
            return(valid);
        }
예제 #26
0
        private void RemoveHyperlinkFormat()
        {
            TextPointer caretPosition     = Selection.Start;
            TextPointer backspacePosition = caretPosition.GetNextInsertionPosition(LogicalDirection.Backward);
            Hyperlink   hyperlink         = default(Hyperlink);

            try
            {
                if (backspacePosition != null && IsHyperlinkBoundaryCrossed(caretPosition, backspacePosition, ref hyperlink))
                {
                    // Remember caretPosition with forward gravity. This is necessary since we are going to delete
                    // the hyperlink element preceding caretPosition and after deletion current caretPosition
                    // (with backward gravity) will follow content preceding the hyperlink.
                    // We want to remember content following the hyperlink to set new caret position at.

                    TextPointer newCaretPosition = caretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);

                    // 1. Copy its children Inline to a temporary array
                    InlineCollection hyperlinkChildren = hyperlink.Inlines;
                    Inline[]         inlines           = new Inline[hyperlinkChildren.Count];
                    hyperlinkChildren.CopyTo(inlines, 0);

                    // 2. Remove each child from parent hyperlink element and insert it after the hyperlink
                    for (int i = inlines.Length - 1; i >= 0; i--)
                    {
                        hyperlinkChildren.Remove(inlines[i]);
                        if (hyperlink.SiblingInlines != null)
                        {
                            hyperlink.SiblingInlines.InsertAfter(hyperlink, inlines[i]);
                        }
                    }

                    // 3. Apply hyperlink local formatting properties to inlines (which are now outside hyperlink scope)
                    LocalValueEnumerator localProperties = hyperlink.GetLocalValueEnumerator();
                    TextRange            inlineRange     = new TextRange(inlines[0].ContentStart, inlines[inlines.Length - 1].ContentEnd);

                    while (localProperties.MoveNext())
                    {
                        LocalValueEntry    property           = localProperties.Current;
                        DependencyProperty dependencyProperty = property.Property;
                        object             value = property.Value;

                        // Ignore hyperlink defaults
                        if (dependencyProperty.ReadOnly == false &&
                            dependencyProperty.Equals(Inline.TextDecorationsProperty) == false &&
                            dependencyProperty.Equals(TextElement.ForegroundProperty) == false &&
                            dependencyProperty.Equals(BaseUriHelper.BaseUriProperty) == false &&
                            IsHyperlinkProperty(dependencyProperty) == false &&
                            dependencyProperty.Name.Equals("IsEnabled") == false)
                        {
                            inlineRange.ApplyPropertyValue(dependencyProperty, value);
                        }
                    }

                    // 4. Delete the (empty) hyperlink element
                    if (hyperlink.SiblingInlines != null)
                    {
                        hyperlink.RequestNavigate -= OnRequestNavigate;
                        hyperlink.SiblingInlines.Remove(hyperlink);
                    }

                    // 5. Update selection, since we deleted Hyperlink element and caretPosition was at that hyperlink's end boundary
                    Selection.Select(newCaretPosition, newCaretPosition);
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error while removing hyperlink format: {EX}", ex);
            }
        }
        /// <summary>
        /// Event handler for KeyDown event to auto-detect hyperlinks on space, enter and backspace keys.
        /// </summary>
        private static void OnKeyDown(object sender, KeyEventArgs e)
        {
            var myRichTextBox = (MyRichTextBox)sender;

            if (e.Key != Key.Space && e.Key != Key.Back && e.Key != Key.Return)
            {
                return;
            }

            if (!myRichTextBox.Selection.IsEmpty)
            {
                myRichTextBox.Selection.Text = String.Empty;
            }

            TextPointer caretPosition = myRichTextBox.Selection.Start;

            if (e.Key == Key.Space || e.Key == Key.Return)
            {
                TextPointer wordStartPosition;
                string      word = GetPreceedingWordInParagraph(caretPosition, out wordStartPosition);

                if (word == "www.microsoft.com")
                // A real app would need a more sophisticated RegEx match expression for hyperlinks.
                {
                    // Insert hyperlink element at word boundaries.
                    var start = wordStartPosition.GetPositionAtOffset(0, LogicalDirection.Backward);
                    var end   = caretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);

                    if (start != null)
                    {
                        if (end != null)
                        {
                            new Hyperlink(start
                                          , end);
                        }
                    }

                    // No need to update RichTextBox caret position,
                    // since we only inserted a Hyperlink ElementEnd following current caretPosition.
                    // Subsequent handling of space input by base RichTextBox will update selection.
                }
            }
            else // Key.Back
            {
                TextPointer backspacePosition = caretPosition.GetNextInsertionPosition(LogicalDirection.Backward);
                Hyperlink   hyperlink;
                if (backspacePosition != null &&
                    IsHyperlinkBoundaryCrossed(caretPosition, backspacePosition, out hyperlink))
                {
                    // Remember caretPosition with forward gravity. This is necessary since we are going to delete
                    // the hyperlink element preceeding caretPosition and after deletion current caretPosition
                    // (with backward gravity) will follow content preceeding the hyperlink.
                    // We want to remember content following the hyperlink to set new caret position at.

                    TextPointer newCaretPosition = caretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);

                    // Deleting the hyperlink is done using logic below.

                    // 1. Copy its children Inline to a temporary array.
                    InlineCollection hyperlinkChildren = hyperlink.Inlines;
                    var inlines = new Inline[hyperlinkChildren.Count];
                    hyperlinkChildren.CopyTo(inlines, 0);

                    // 2. Remove each child from parent hyperlink element and insert it after the hyperlink.
                    for (int i = inlines.Length - 1; i >= 0; i--)
                    {
                        hyperlinkChildren.Remove(inlines[i]);
                        if (hyperlink.SiblingInlines != null)
                        {
                            hyperlink.SiblingInlines.InsertAfter(hyperlink, inlines[i]);
                        }
                    }

                    // 3. Apply hyperlink's local formatting properties to inlines (which are now outside hyperlink scope).
                    LocalValueEnumerator localProperties = hyperlink.GetLocalValueEnumerator();
                    var inlineRange = new TextRange(inlines[0].ContentStart, inlines[inlines.Length - 1].ContentEnd);

                    while (localProperties.MoveNext())
                    {
                        LocalValueEntry    property = localProperties.Current;
                        DependencyProperty dp       = property.Property;
                        object             value    = property.Value;

                        if (!dp.ReadOnly &&
                            dp != Inline.TextDecorationsProperty && // Ignore hyperlink defaults.
                            dp != TextElement.ForegroundProperty &&
                            !IsHyperlinkProperty(dp))
                        {
                            inlineRange.ApplyPropertyValue(dp, value);
                        }
                    }

                    // 4. Delete the (empty) hyperlink element.
                    if (hyperlink.SiblingInlines != null)
                    {
                        hyperlink.SiblingInlines.Remove(hyperlink);
                    }

                    // 5. Update selection, since we deleted Hyperlink element and caretPosition was at that Hyperlink's end boundary.
                    if (newCaretPosition != null)
                    {
                        myRichTextBox.Selection.Select(newCaretPosition, newCaretPosition);
                    }
                }
            }
        }
예제 #28
0
        private ArrayList SaveSubStreams(UIElement element)
        {
            ArrayList subStreams = null;

#pragma warning disable 618
            if ((element != null) && (element.PersistId != 0))
#pragma warning restore 618
            {
                LocalValueEnumerator dpEnumerator = element.GetLocalValueEnumerator();

                while (dpEnumerator.MoveNext())
                {
                    LocalValueEntry           localValueEntry = (LocalValueEntry)dpEnumerator.Current;
                    FrameworkPropertyMetadata metadata        = localValueEntry.Property.GetMetadata(element.DependencyObjectType) as FrameworkPropertyMetadata;

                    if (metadata == null)
                    {
                        continue;
                    }

                    // To be saved, a DP should have the correct metadata and NOT be an expression or data bound.
                    // Since Bind inherits from Expression, the test for Expression will suffice.
                    // NOTE: we do not journal expression. So we should let parser restore it in BamlRecordReader.SetDependencyValue.
                    // Please see Windows OS
                    if (metadata.Journal && (!(localValueEntry.Value is Expression)))
                    {
                        // These properties should not be journaled.
                        //

                        if (object.ReferenceEquals(localValueEntry.Property, Frame.SourceProperty))
                        {
                            continue;
                        }

                        if (subStreams == null)
                        {
                            subStreams = new ArrayList(3);
                        }

                        object currentValue = element.GetValue(localValueEntry.Property);
                        byte[] bytes        = null;

                        if ((currentValue != null) && !(currentValue is Uri))
                        {
                            // Convert the value of the DP into a byte array
                            MemoryStream byteStream = new MemoryStream();
                            new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).Assert();
                            try
                            {
                                this.Formatter.Serialize(byteStream, currentValue);
                            }
                            finally
                            {
                                SecurityPermission.RevertAssert();
                            }

                            bytes = byteStream.ToArray();
                            // Dispose the stream
                            ((IDisposable)byteStream).Dispose( );
                        }

                        // Save the byte array by the property name
                        subStreams.Add(new SubStream(localValueEntry.Property.Name, bytes));
                    }
                }
            }

            return(subStreams);
        }
예제 #29
0
        /// <summary>
        /// Validates a WPF tree to determine if binding errors exist
        /// </summary>
        /// <param name="parent">Parent DependencyObject</param>
        /// <returns>True if no errors exist</returns>
        public static bool IsValid(DependencyObject parent)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }

            // note that this goes wrong in a data template
            // http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/d88f3926-68e5-488d-9fb1-a9f94a5ffd11
            // http://stackoverflow.com/questions/338522/getlocalvalueenumerator-not-returning-all-properties

            bool valid = true;

            // validate parent
            LocalValueEnumerator localValueEnumerator = parent.GetLocalValueEnumerator();

            while (localValueEnumerator.MoveNext())
            {
                LocalValueEntry entry = localValueEnumerator.Current;

                if (BindingOperations.IsDataBound(parent, entry.Property))
                {
                    Binding binding = BindingOperations.GetBinding(parent, entry.Property);
                    if (binding.Path.Path.Contains("Search"))
                    {
                        Debug.WriteLine("Search");
                    }
                    if ((binding.Mode == BindingMode.TwoWay) || (binding.Mode == BindingMode.OneWayToSource))
                    {
                        BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property);
                        expression.UpdateSource();
                        if (expression.HasError)
                        {
                            valid = false;
                        }
                    }
                }
            }

            // validate logical children
            bool        foundLogicalChildren = false;
            IEnumerable children             = LogicalTreeHelper.GetChildren(parent);

            foreach (object obj in children)
            {
                foundLogicalChildren = true;

                DependencyObject child = obj as DependencyObject;
                if (child != null)
                {
                    if (!IsValid(child))
                    {
                        valid = false;
                    }
                }
            }

            // if no logical children found try looking for visual children
            if ((!foundLogicalChildren) && (parent is Visual))
            {
                int visualChildrenCount = VisualTreeHelper.GetChildrenCount(parent);
                if (visualChildrenCount > 0)
                {
                    for (int child = 0; child < visualChildrenCount; child++)
                    {
                        if (!IsValid(VisualTreeHelper.GetChild(parent, child)))
                        {
                            valid = false;
                        }
                    }
                }
            }

            return(valid);
        }