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); }
/// <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); }
/// <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); } }
public void TestEnumerationOfAttachedProperties() { int count = 0; Y y = new Y(); X.SetA(y, 2); X.SetB(y, "Hi"); LocalValueEnumerator e = y.GetLocalValueEnumerator(); while (e.MoveNext()) { count++; if (e.Current.Property == X.AProperty) { Assert.AreEqual(e.Current.Value, 2); } else if (e.Current.Property == X.BProperty) { Assert.AreEqual(e.Current.Value, "Hi"); } else { Assert.Fail("Wrong sort of property" + e.Current.Property); } } Assert.AreEqual(2, count); }
protected static bool Freeze(Freezable freezable, bool isChecking) { if (freezable.frozen) { return(true); } LocalValueEnumerator e = freezable.GetLocalValueEnumerator(); while (e.MoveNext()) { var value = e.Current.Value; if (value is Freezable) { if (!(value as Freezable).FreezeCore(isChecking)) { return(false); } } } if (!isChecking) { freezable.frozen = true; } return(true); }
/// <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]); } }
// 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); }
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) { } } } } } }
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); } }
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); }
//https://stackoverflow.com/questions/4794071/how-to-enumerate-all-dependency-properties-of-control public static IEnumerable <DependencyProperty> EnumerateDependencyProperties(this DependencyObject obj) { if (obj != null) { LocalValueEnumerator lve = obj.GetLocalValueEnumerator(); while (lve.MoveNext()) { yield return(lve.Current.Property); } } }
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); } }
public static void UpdateBindingSources(this DependencyObject dependencyObject) { foreach (DependencyObject element in dependencyObject.EnumerateVisualDescendents()) { LocalValueEnumerator localValueEnumerator = element.GetLocalValueEnumerator(); while (localValueEnumerator.MoveNext()) { BindingExpressionBase bindingExpression = BindingOperations.GetBindingExpressionBase(element, localValueEnumerator.Current.Property); bindingExpression?.UpdateSource(); } } }
public static IEnumerable <DependencyObject> GetAllDescendantWithProperty(this DependencyObject dependencyObject, string propertyName) { foreach (DependencyObject element in dependencyObject.EnumerateVisualDescendents()) { LocalValueEnumerator localValueEnumerator = element.GetLocalValueEnumerator(); while (localValueEnumerator.MoveNext()) { if (localValueEnumerator.Current.Property.Name == propertyName) { yield return(element); } } } }
DependencyProperty FindProperty(DependencyObject element, string propName) { LocalValueEnumerator lve = element.GetLocalValueEnumerator(); while (lve.MoveNext()) { if (lve.Current.Property.Name == propName) { return(lve.Current.Property); } } return(null); }
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); } } }
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); }
public override void Render(DrawingContext dc, Point screenPoint) { LocalValueEnumerator enumerator = GetLocalValueEnumerator(); foreach (var marker in markers) { enumerator.Reset(); while (enumerator.MoveNext()) { marker.SetValue(enumerator.Current.Property, enumerator.Current.Value); } marker.Render(dc, screenPoint); } }
public static void UpdateBindingTargets(this DependencyObject dependencyObject) { foreach (DependencyObject element in dependencyObject.EnumerateVisualDescendents()) { LocalValueEnumerator localValueEnumerator = element.GetLocalValueEnumerator(); while (localValueEnumerator.MoveNext()) { BindingExpressionBase bindingExpression = BindingOperations.GetBindingExpressionBase(element, localValueEnumerator.Current.Property); bindingExpression?.UpdateTarget(); } var itemsControl = element as ItemsControl; itemsControl?.Items.Refresh(); } }
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)); } } } } }
/// <summary> /// Gets all dependency properties that have local values set. /// </summary> /// <param name="obj">Object instance.</param> /// <returns>Returns System.Collections.Generic.Dictionary(string, DependencyProperty) object.</returns> public static Dictionary <string, DependencyProperty> WpfLocalOnlyDependencyProperties(DependencyObject obj) { Dictionary <string, DependencyProperty> result = new Dictionary <string, DependencyProperty>(); if (obj != null) { LocalValueEnumerator lve = obj.GetLocalValueEnumerator(); while (lve.MoveNext()) { DependencyProperty depProp = lve.Current.Property; string name = depProp.OwnerType.Name + "." + depProp.Name; result[depProp.Name] = depProp; result[name] = depProp; } } return(result); }
private void UpdateSources(DependencyObject current) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(current); i++) { DependencyObject child = VisualTreeHelper.GetChild(current, i); LocalValueEnumerator props = child.GetLocalValueEnumerator(); while (props.MoveNext()) { BindingExpression binding = BindingOperations.GetBindingExpression(child, props.Current.Property); if (binding != null) { binding.UpdateSource(); } } UpdateSources(child); } }
//<SnippetIterateLocalValuesAndClear> void RestoreDefaultProperties(object sender, RoutedEventArgs e) { UIElementCollection uic = Sandbox.Children; foreach (Shape uie in uic) { LocalValueEnumerator locallySetProperties = uie.GetLocalValueEnumerator(); while (locallySetProperties.MoveNext()) { DependencyProperty propertyToClear = locallySetProperties.Current.Property; if (!propertyToClear.ReadOnly) { uie.ClearValue(propertyToClear); } } } }
public static void ResetControlText <T>(Window currentWindow) where T : DependencyObject { currentWindow.Visibility = Visibility.Hidden; foreach (T item in FindVisualChildren <T>(currentWindow)) { //item.ClearValue(TextBlock.TextProperty); LocalValueEnumerator locallySetProperties = item.GetLocalValueEnumerator(); while (locallySetProperties.MoveNext()) { DependencyProperty propertyToClear = locallySetProperties.Current.Property; if (propertyToClear.Name == "Text") { item.ClearValue(propertyToClear); } } } }
/// <summary> /// Flushes all bindings for the specified <see cref="DependencyObject"/> and all of its descendents. /// </summary> /// <param name="dependencyObject">The dependency object.</param> //public static void FlushBindings (this DependencyObject dependencyObject) ** Uncomment when we have C# 3.0 support ** public static void FlushBindings(DependencyObject dependencyObject) { //foreach (DependencyObject element in dependencyObject.EnumerateVisualDescendents ()) ** Uncomment when we have C# 3.0 support ** foreach (DependencyObject element in Extensions.EnumerateVisualDescendents(dependencyObject)) { LocalValueEnumerator localValueEnumerator = element.GetLocalValueEnumerator(); while (localValueEnumerator.MoveNext()) { BindingExpressionBase bindingExpression = BindingOperations.GetBindingExpressionBase(element, localValueEnumerator.Current.Property); if (bindingExpression != null) { bindingExpression.UpdateSource(); bindingExpression.UpdateTarget(); } } } }
/// <summary> /// Locates a dependency property that has a local value set. /// </summary> /// <param name="propertyName">Property name may be in format OwnerType.PropertyName' .</param> /// <param name="obj">Object instance.</param> /// <returns> Returns System.Windows.DependencyProperty object or null.</returns> public static DependencyProperty WpfLocateLocalOnlyDependencyProperty(string propertyName, DependencyObject obj) { if (obj != null) { LocalValueEnumerator lve = obj.GetLocalValueEnumerator(); while (lve.MoveNext()) { DependencyProperty depProp = lve.Current.Property; var nameArr = depProp.Name.Split('.'); // ignore the Shadow suffix var propName = nameArr[0]; // remove shadow name decorators if ((propName == propertyName) || (depProp.OwnerType.Name + "." + propName == propertyName)) { return(depProp); } } } return(null); }
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); } }
/// <summary> /// Sets local values on the text element scoping position. /// </summary> /// <param name="position"> /// A position scoped by the element on which to set the property. /// </param> /// <param name="values"> /// Values to set. /// </param> /// <exception cref="System.InvalidOperationException"> /// Throws InvalidOperationException if position is not scoped by a /// text element or if a property value may not be applied on the /// scoping text element. /// </exception> internal void SetValues(TextPointer position, LocalValueEnumerator values) { TextElement textElement; LocalValueEntry property; // VerifyAccess(); if (position == null) { throw new ArgumentNullException("position"); } // LocalValueEnumerator is a struct. // if (values == null) // { // throw new ArgumentNullException("values"); // } EmptyDeadPositionList(); ValidateSetValue(position); BeginChange(); try { textElement = position.Parent as TextElement; Invariant.Assert(textElement != null); values.Reset(); while (values.MoveNext()) { property = values.Current; // if (property.Property.Name == "CachedSource") { continue; } // If the property is readonly on the text element, then we shouldn't // try to copy the property value. if (property.Property.ReadOnly) { continue; } // Don't copy over Run.Text. This will get automatically invalidated by TextContainer // when the Run's text content is set. Setting this property now will cause TextContainer // changes that get us into trouble in the middle of undo. if (property.Property == Run.TextProperty) { continue; } BindingExpressionBase expr = property.Value as BindingExpressionBase; if (expr != null) { // We can't duplicate a binding so copy over the current value instead. textElement.SetValue(property.Property, expr.Value); } else { textElement.SetValue(property.Property, property.Value); } } } finally { EndChange(); } }
// Copies a LocalValueEnumerator properties into an array of DependencyProperty. // This method is useful because LocalValueEnumerator does not support // setting or clearing local values while enumerating. private DependencyProperty[] LocalValueEnumeratorToArray(LocalValueEnumerator valuesEnumerator) { DependencyProperty[] properties; int count; properties = new DependencyProperty[valuesEnumerator.Count]; count = 0; valuesEnumerator.Reset(); while (valuesEnumerator.MoveNext()) { properties[count++] = valuesEnumerator.Current.Property; } return properties; }