static BindingExpression GetBindingExp(DependencyObject d, DependencyProperty dp) { #if !SILVERLIGHT return BindingOperations.GetBindingExpression(d, dp); #else if(d is FrameworkElement) return ((FrameworkElement)d).GetBindingExpression(dp); return d.ReadLocalValue(dp) as BindingExpression; #endif }
/// <summary> /// Generates control fields /// </summary> /// <param name="source">The source.</param> /// <param name="classType">Type of the class.</param> /// <param name="method">The method.</param> /// <param name="generateField">if set to <c>true</c> [generate field].</param> /// <returns></returns> public virtual CodeExpression Generate(DependencyObject source, CodeTypeDeclaration classType, CodeMemberMethod method, bool generateField) { DataGridColumn column = source as DataGridColumn; string typeName = source.GetType().Name; string name = ColumnName; CodeExpression fieldReference = new CodeVariableReferenceExpression(name); CodeTypeReference variableType = new CodeTypeReference(typeName); CodeVariableDeclarationStatement declaration = new CodeVariableDeclarationStatement(variableType, name); declaration.InitExpression = new CodeObjectCreateExpression(typeName); method.Statements.Add(declaration); if (CodeComHelper.IsValidForFieldGenerator(source.ReadLocalValue(DataGridColumn.WidthProperty))) { DataGridLength value = (DataGridLength)source.GetValue(DataGridColumn.WidthProperty); if (value.UnitType == DataGridLengthUnitType.Pixel) { method.Statements.Add(new CodeAssignStatement( new CodeFieldReferenceExpression(fieldReference, DataGridColumn.WidthProperty.Name), new CodePrimitiveExpression((float)value.Value))); } } CodeComHelper.GenerateFieldDoubleToFloat(method, fieldReference, source, DataGridColumn.MaxWidthProperty); CodeComHelper.GenerateFieldDoubleToFloat(method, fieldReference, source, DataGridColumn.MinWidthProperty); CodeComHelper.GenerateEnumField<Visibility>(method, fieldReference, source, DataGridColumn.VisibilityProperty); CodeComHelper.GenerateField<string>(method, fieldReference, source, DataGridColumn.SortMemberPathProperty); UIElement header = column.Header as UIElement; if (header != null) { TypeGenerator headerGenerator = new TypeGenerator(); CodeExpression headerExpr = headerGenerator.ProcessGenerators(header, classType, method, false); method.Statements.Add(new CodeAssignStatement( new CodeFieldReferenceExpression(fieldReference, "Header"), headerExpr)); } else if (column.Header != null) { CodeComHelper.GenerateField<object>(method, fieldReference, source, DataGridColumn.HeaderProperty); // TODO content can be another class, so this will not work } CodeComHelper.GenerateTemplateStyleField(classType, method, fieldReference, source, DataGridColumn.HeaderStyleProperty, name + "_h"); return fieldReference; }
/// <summary> /// Generates control fields /// </summary> /// <param name="source">The source.</param> /// <param name="classType">Type of the class.</param> /// <param name="method">The initialize method.</param> /// <param name="generateField">if set to <c>true</c> [generate field].</param> /// <returns></returns> public override CodeExpression Generate(DependencyObject source, CodeTypeDeclaration classType, CodeMemberMethod method, bool generateField) { CodeExpression fieldReference = base.Generate(source, classType, method, generateField); Path path = source as Path; if (CodeComHelper.IsValidForFieldGenerator(source.ReadLocalValue(Path.DataProperty))) { CodeExpression dataValueExpression = CodeComHelper.GetValueExpression(classType, method, path.Data, path.Name + "_G"); method.Statements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(path.Name), "Data"), dataValueExpression)); } return fieldReference; }
} // OnDependencyPropertyChanged // ---------------------------------------------------------------------- private static ApplicationSettings FindParentSettings(DependencyObject element) { while (element != null) { ApplicationSettings applicationSettings = element.ReadLocalValue(ApplicationSettingsProperty) as ApplicationSettings; if (applicationSettings != null) { return applicationSettings; } element = LogicalTreeHelper.GetParent(element); } return null; } // FindParentSettings
//----------------------------------------------------- // // Public Methods // //------------------------------------------------------ /// <summary> Returns the referenced object. </summary> /// <param name="d">Element defining context for the reference. </param> /// <param name="args">See ObjectRefArgs </param> internal override object GetObject(DependencyObject d, ObjectRefArgs args) { if (d == null) throw new ArgumentNullException("d"); object o = null; if (args.ResolveNamesInTemplate) { // look in container's template (if any) first FrameworkElement fe = d as FrameworkElement; if (fe != null && fe.TemplateInternal != null) { o = Helper.FindNameInTemplate(_name, d); if (args.IsTracing) { TraceData.Trace(TraceEventType.Warning, TraceData.ElementNameQueryTemplate( _name, TraceData.Identify(d))); } } if (o == null) { args.NameResolvedInOuterScope = true; } } FrameworkObject fo = new FrameworkObject(d); while (o == null && fo.DO != null) { DependencyObject scopeOwner; o = fo.FindName(_name, out scopeOwner); // if the original element is a scope owner, supports IComponentConnector, // and has a parent, don't use the result of FindName. The // element is probably an instance of a Xaml-subclassed control; // we want to resolve the name starting in the next outer scope. // (bug 1669408) // Also, if the element's NavigationService property is locally // set, the element is the root of a navigation and should use the // inner scope (bug 1765041) if (d == scopeOwner && d is IComponentConnector && d.ReadLocalValue(System.Windows.Navigation.NavigationService.NavigationServiceProperty) == DependencyProperty.UnsetValue) { DependencyObject parent = LogicalTreeHelper.GetParent(d); if (parent == null) { parent = Helper.FindMentor(d.InheritanceContext); } if (parent != null) { o = null; fo.Reset(parent); continue; } } if (args.IsTracing) { TraceData.Trace(TraceEventType.Warning, TraceData.ElementNameQuery( _name, TraceData.Identify(fo.DO))); } if (o == null) { args.NameResolvedInOuterScope = true; // move to the next outer namescope. // First try TemplatedParent of the scope owner. FrameworkObject foScopeOwner = new FrameworkObject(scopeOwner); DependencyObject dd = foScopeOwner.TemplatedParent; // if that doesn't work, we could be at the top of // generated content for an ItemsControl. If so, use // the (visual) parent - a panel. if (dd == null) { Panel panel = fo.FrameworkParent.DO as Panel; if (panel != null && panel.IsItemsHost) { dd = panel; } } // next, see if we're in a logical tree attached directly // to a ContentPresenter. This is the m---- equivalent of // having the ContentPresenter as the TemplatedParent. if (dd == null && scopeOwner == null) { // go to the top of the logical subtree DependencyObject parent; for (dd = fo.DO;;) { parent = LogicalTreeHelper.GetParent(dd); if (parent == null) { parent = Helper.FindMentor(dd.InheritanceContext); } if (parent == null) break; dd = parent; } // if it's attached to a ContentPresenter, move to the CP ContentPresenter cp = VisualTreeHelper.IsVisualType(dd) ? VisualTreeHelper.GetParent(dd) as ContentPresenter : null; dd = (cp != null && cp.TemplateInternal.CanBuildVisualTree) ? cp : null; } fo.Reset(dd); } } if (o == null) { o = DependencyProperty.UnsetValue; args.NameResolvedInOuterScope = false; } return o; }
///<summary> /// Checks if the <see cref="ActionMessage"/>-Target was set. ///</summary> ///<param name="element">DependencyObject to check</param> ///<returns>True if Target or TargetWithoutContext was set on <paramref name="element"/></returns> public static bool HasTargetSet(DependencyObject element) { return (element.ReadLocalValue(TargetProperty) != DependencyProperty.UnsetValue) || (element.ReadLocalValue(TargetWithoutContextProperty) != DependencyProperty.UnsetValue); }
private static ScrollSyncType readSyncTypeDPValue(DependencyObject d, DependencyProperty dp) { var value = d.ReadLocalValue(dp); return (value == DependencyProperty.UnsetValue ? ScrollSyncType.None : (ScrollSyncType)value); }
/// <summary> /// Check whether xxxTemplate property is set on the given element. /// Only explicit local values or resource references count; data-bound or templated values don't count. /// </summary> internal static bool IsTemplateDefined(DependencyProperty templateProperty, DependencyObject d) { // Check whether xxxTemplate property is set on the given element. object template = d.ReadLocalValue(templateProperty); // the checks for UnsetValue and null are for perf: // they're redundant to the type checks, but they're cheaper return (template != DependencyProperty.UnsetValue && template != null && (template is FrameworkTemplate || template is ResourceReferenceExpression)); }
void GenerateReadLocalValueTests (DependencyObject widget, Type type) { DependencyProperty property; FieldInfo[] fields; Type ctype = type; string method; object retval; while (ctype.IsSubclassOf (typeof (DependencyObject)) && !ctype.IsGenericType) { fields = ctype.GetFields (); bool emit_test = false; for (int i = 0; i < fields.Length; i++) { if (!fields[i].IsPublic || !fields[i].IsStatic || fields[i].FieldType != typeof (DependencyProperty)) continue; try { property = fields[i].GetValue (null) as DependencyProperty; } catch { property = null; } if (property == null) continue; emit_test = true; break; } if (emit_test) { EmitTestMethod (type, "ReadLocalValue_" + PrettyName(ctype), true); for (int i = 0; i < fields.Length; i++) { if (!fields[i].IsPublic || !fields[i].IsStatic || fields[i].FieldType != typeof (DependencyProperty)) continue; try { property = fields[i].GetValue (null) as DependencyProperty; } catch { property = null; } if (property == null) continue; method = "ReadLocalValue(" + ctype.Name + "." + fields[i].Name + ")"; try { retval = widget.ReadLocalValue (property); sb.AppendLine (" retval = widget." + method + ";"); if (retval != DependencyProperty.UnsetValue) { if (retval != null) { sb.AppendLine (" Assert.IsNotNull(retval, \"" + method + " should not have returned null\");"); AssertValuesEqual (widget, type, method, "retval", retval, true); } else { sb.AppendLine (" Assert.IsNull(retval, \"" + method + " should have returned null\");"); } } else { sb.AppendLine (" Assert.AreEqual(DependencyProperty.UnsetValue, retval, \"" + method + " should not have a value by default\");"); } } catch (Exception ex) { sb.AppendLine (" // [MoonlightBug] - Moonlight needs to be fixed to throw on some ReadLocalValue invocations"); sb.AppendLine (" //Assert.Throws<" + ex.GetType ().Name + ">(delegate {"); sb.AppendLine (" // retval = widget." + method + ";"); sb.AppendLine (" //}, \"" + method + " should thow an exception\");"); } } sb.AppendLine (" }"); sb.AppendLine (); } ctype = ctype.BaseType; } }
/// <summary> /// Determines whether or not a DependencyObject has the WindowMovement.DragsWindow property set to true. /// </summary> /// <param name="visual">The DependencyObject to test for the property on.</param> /// <returns>true if the object has the attached property and it is set to true.</returns> public static bool HasDragsWindowEnabled(DependencyObject visual) { var dragsWindow = visual.ReadLocalValue(DragsWindow); return (dragsWindow != DependencyProperty.UnsetValue && (bool) dragsWindow); }
//------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods private void ApplyItemContainerStyle(DependencyObject container, object item) { FrameworkObject foContainer = new FrameworkObject(container); // don't overwrite a locally-defined style (bug 1018408) if (!foContainer.IsStyleSetFromGenerator && container.ReadLocalValue(FrameworkElement.StyleProperty) != DependencyProperty.UnsetValue) { return; } // Control's ItemContainerStyle has first stab Style style = ItemContainerStyle; // no ItemContainerStyle set, try ItemContainerStyleSelector if (style == null) { if (ItemContainerStyleSelector != null) { style = ItemContainerStyleSelector.SelectStyle(item, container); } } // apply the style, if found if (style != null) { // verify style is appropriate before applying it if (!style.TargetType.IsInstanceOfType(container)) throw new InvalidOperationException(SR.Get(SRID.StyleForWrongType, style.TargetType.Name, container.GetType().Name)); foContainer.Style = style; foContainer.IsStyleSetFromGenerator = true; } else if (foContainer.IsStyleSetFromGenerator) { // if Style was formerly set from ItemContainerStyle, clear it foContainer.IsStyleSetFromGenerator = false; container.ClearValue(FrameworkElement.StyleProperty); } }
internal static bool IsTemplateSelectorDefined(DependencyProperty templateSelectorProperty, DependencyObject d) { object obj = d.ReadLocalValue(templateSelectorProperty); return obj != DependencyProperty.UnsetValue && obj != null && (obj is DataTemplateSelector);// || obj is ResourceReferenceExpression); }
private void CopyBrushes(DependencyObject dst, DependencyObject src) { if (src != null && dst != null && src.GetType() == dst.GetType()) { Type type = dst.GetType(); BindingFlags bindingFlag = BindingFlags.Static | BindingFlags.Public; if (typeof (Polygon).IsAssignableFrom(type)) { bindingFlag = bindingFlag | BindingFlags.FlattenHierarchy; } FieldInfo[] fields = type.GetFields(bindingFlag); for (int i = 0; i < fields.Length; i++) { DependencyProperty value = fields[i].GetValue(null) as DependencyProperty; if (value != null) { Brush brush = src.ReadLocalValue(value) as Brush; if (brush != null) { dst.SetValue(value, brush); } } } if (src is Border && dst is Border) { CopyBrushes(((Border) dst).Child, ((Border) src).Child); return; } if (src is Panel && dst is Panel) { UIElementCollection children = ((Panel) src).Children; UIElementCollection uIElementCollections = ((Panel) dst).Children; if (children.Count == uIElementCollections.Count) { for (int j = 0; j < children.Count; j++) { CopyBrushes(uIElementCollections[j], children[j]); } } } } }
private static IEnumerable<string> GetBindingPaths(DependencyObject element) { var properties = GetDependencyProperties(element); foreach (var property in properties) { var expression = element.ReadLocalValue(property) as BindingExpression; if(expression != null && expression.ParentBinding != null && expression.ParentBinding.Path != null) yield return expression.ParentBinding.Path.Path; } }
void GenerateSetStringValueTests (DependencyObject widget, Type type) { DependencyProperty property; PropertyInfo[] properties; bool testing = false; Type ctype = type; string prop_name; string actual; string method; object retval; while (ctype.IsSubclassOf (typeof (DependencyObject)) && !ctype.IsGenericType) { properties = ctype.GetProperties (); bool emit_test = false; for (int i = 0; i < properties.Length; i++) { if (properties[i].PropertyType != typeof (string)) continue; prop_name = properties[i].Name + "Property"; property = GetDependencyPropertyByName (widget, ctype, prop_name); if (property == null) continue; emit_test = true; break; } if (emit_test) { EmitTestMethod (type, "SetStringValue_" + PrettyName (ctype), true); // Note: we iterate over the getter/setter properties because the DependencyProperties do not have type information for (int i = 0; i < properties.Length; i++) { if (properties[i].PropertyType != typeof (string)) continue; prop_name = properties[i].Name + "Property"; property = GetDependencyPropertyByName (widget, ctype, prop_name); if (property == null) continue; // First thing we try is setting the string to something method = "SetValue(" + ctype.Name + "." + prop_name + ", \"some text\")"; try { widget.SetValue (property, "some text"); sb.AppendLine (" widget." + method + ";"); } catch (Exception ex) { sb.AppendLine (" Assert.Throws<" + ex.GetType ().Name + ">(delegate {"); sb.AppendLine (" widget." + method + ";"); sb.AppendLine (" }, \"" + method.Replace ("\"","\\\"") + " should thow an exception\");"); } // Then we check that the value is what we we just set method = "GetValue(" + ctype.Name + "." + prop_name + ")"; try { retval = widget.GetValue (property); actual = retval as string; sb.AppendLine (" retval = widget." + method + ";"); if (actual == "some text") { sb.AppendLine (" Assert.AreEqual(\"some text\", retval, \"" + method + " should have returned 'some text'\");"); } else if (actual != null) { sb.AppendLine (" Assert.AreEqual(\"" + actual + "\", retval, \"" + method + " should have returned '" + actual + "'\");"); } else { sb.AppendLine (" Assert.IsNull(retval, \"" + method + " should have returned null\");"); } } catch (Exception ex) { sb.AppendLine (" Assert.Throws<" + ex.GetType ().Name + ">(delegate {"); sb.AppendLine (" retval = widget." + method + ";"); sb.AppendLine (" }, \"" + method + " should thow an exception\");"); } // Next we try setting the string to null to see if it will let us method = "SetValue(" + ctype.Name + "." + prop_name + ", null)"; try { widget.SetValue (property, null); sb.AppendLine (" widget." + method + ";"); } catch (Exception ex) { sb.AppendLine (" Assert.Throws<" + ex.GetType ().Name + ">(delegate {"); sb.AppendLine (" widget." + method + ";"); sb.AppendLine (" }, \"" + method + " should thow an exception\");"); } // Then we check that the value was actually set to null as opposed to String.Empty method = "GetValue(" + ctype.Name + "." + prop_name + ")"; try { retval = widget.GetValue (property); actual = retval as string; sb.AppendLine (" retval = widget." + method + ";"); if (actual == String.Empty) { sb.AppendLine (" Assert.AreEqual(String.Empty, retval, \"" + method + " should have returned String.Empty\");"); } else if (actual != null) { sb.AppendLine (" Assert.AreEqual(\"" + actual + "\", retval, \"" + method + " should have returned '" + actual + "'\");"); } else { sb.AppendLine (" Assert.IsNull(retval, \"" + method + " should have returned null\");"); } } catch (Exception ex) { sb.AppendLine (" Assert.Throws<" + ex.GetType ().Name + ">(delegate {"); sb.AppendLine (" retval = widget." + method + ";"); sb.AppendLine (" }, \"" + method + " should thow an exception\");"); retval = actual = null; } // If the GetValue returned String.Empty, then we need to check ReadLocalValue to see wtf is going on if (actual == String.Empty) { method = "ReadLocalValue(" + PrettyName (ctype) + "." + prop_name + ")"; try { retval = widget.ReadLocalValue (property); sb.AppendLine (" retval = widget." + method + ";"); if (retval != DependencyProperty.UnsetValue) { actual = retval as string; if (actual == String.Empty) { sb.AppendLine (" Assert.AreEqual(String.Empty, retval, \"" + method + " should have returned String.Empty\");"); } else if (actual != null) { sb.AppendLine (" Assert.AreEqual(\"" + actual + "\", retval, \"" + method + " should have returned '" + actual + "'\");"); } else { sb.AppendLine (" Assert.IsNull(retval, \"" + method + " should have returned null\");"); } } else { sb.AppendLine (" Assert.AreEqual(DependencyProperty.UnsetValue, retval, \"" + method + " should not have a value by default\");"); } } catch (Exception ex) { sb.AppendLine (" // [MoonlightBug] - Moonlight needs to be fixed to throw on some ReadLocalValue invocations"); sb.AppendLine (" //Assert.Throws<" + ex.GetType ().Name + ">(delegate {"); sb.AppendLine (" // retval = widget." + method + ";"); sb.AppendLine (" //}, \"" + method + " should thow an exception\");"); } } } sb.AppendLine (" }"); sb.AppendLine (); } ctype = ctype.BaseType; } }
/// <summary> /// This method is called after PreProcessNode and after all the children /// in the subtree have been processed (or skipped if PreProcessNode returns /// true for calledProcessAnnotations). /// If no calls to ProcessAnnotations were made for any portion of the subtree below /// this node, then annotations for this node will be loaded /// </summary> /// <param name="node">the node to process</param> /// <param name="childrenCalledProcessAnnotations">indicates whether calledProcessAnnotations /// was returned as true by any node underneath this node</param> /// <param name="calledProcessAnnotations">indicates whether ProcessAnnotations was called /// by this method</param> /// <returns> /// a list of AttachedAnnotations loaded during the processing of /// the node; can be null if no annotations were loaded /// </returns> public override IList<IAttachedAnnotation> PostProcessNode(DependencyObject node, bool childrenCalledProcessAnnotations, out bool calledProcessAnnotations) { if (node == null) throw new ArgumentNullException("node"); // We get the local value so we can distinguish between the property // being set or not. We don't want to rely on null or String.Empty because // those might have been the values set. object dataId = node.ReadLocalValue(DataIdProcessor.DataIdProperty); bool fetchAsBatch = (bool) node.GetValue(FetchAnnotationsAsBatchProperty); // If no children were processed, we try and process this node if (!fetchAsBatch && !childrenCalledProcessAnnotations && dataId != DependencyProperty.UnsetValue) { FrameworkElement nodeParent = null; FrameworkElement feNode = node as FrameworkElement; if (feNode != null) { nodeParent = feNode.Parent as FrameworkElement; } AnnotationService service = AnnotationService.GetService(node); if (service != null && (service.Root == node || (nodeParent != null && service.Root == nodeParent.TemplatedParent))) { calledProcessAnnotations = true; return Manager.ProcessAnnotations(node); } } calledProcessAnnotations = false; return null; }
/// <summary> /// Detaches an undo service from the given FrameworkElement. /// </summary> /// <param name="scope"> /// A FrameworkElement with UndoManager attached to it. /// </param> /// <remarks> /// Throws an exception if the scope does not have undo service attached to it. /// </remarks> internal static void DetachUndoManager(DependencyObject scope) { UndoManager undoManager; if (scope == null) { throw new ArgumentNullException("scope"); } // Detach existing undo service if any undoManager = scope.ReadLocalValue(UndoManager.UndoManagerInstanceProperty) as UndoManager; if (undoManager != null) { // Disable the service while in detached state undoManager.IsEnabled = false; // Remove the service from a tre scope.ClearValue(UndoManager.UndoManagerInstanceProperty); // Break the linkage to its scope if (undoManager is UndoManager) { Debug.Assert(((UndoManager)undoManager)._scope == scope); ((UndoManager)undoManager)._scope = null; } } }
//------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// If and only if the current node has a DataId set and has FetchAnnotationsAsBatch /// set to true, then all annotations for the subtree rooted at this node are loaded /// at once. /// </summary> /// <param name="node">node to process</param> /// <param name="calledProcessAnnotations">indicates the callback was called by /// this processor</param> /// <returns> /// a list of AttachedAnnotations loaded during the processing of /// the node; can be null if no annotations were loaded /// </returns> /// <exception cref="ArgumentNullException">node is null</exception> public override IList<IAttachedAnnotation> PreProcessNode(DependencyObject node, out bool calledProcessAnnotations) { if (node == null) throw new ArgumentNullException("node"); // We get the local value so we can distinguish between the property // being set or not. We don't want to rely on null or String.Empty because // those might have been the values set. object dataId = node.ReadLocalValue(DataIdProcessor.DataIdProperty); bool fetchAsBatch = (bool) node.GetValue(FetchAnnotationsAsBatchProperty); // If the current node has an ID set on it and FetchAnnotationsAsBatch is // set to true, we process this node immediately and return. All its children // will be processed indirectly. if (fetchAsBatch && dataId != DependencyProperty.UnsetValue) { calledProcessAnnotations = true; return Manager.ProcessAnnotations(node); } calledProcessAnnotations = false; return null; }
/// <summary> /// Issue a trace message if both the xxxStyle and xxxStyleSelector /// properties are set on the given element. /// </summary> internal static void CheckStyleAndStyleSelector(string name, DependencyProperty styleProperty, DependencyProperty styleSelectorProperty, DependencyObject d) { // Issue a trace message if user defines both xxxStyle and xxxStyleSelector // (bugs 1007020, 1019240). Only explicit local values or resource // references count; data-bound or styled values don't count. // Do not throw here (bug 1434271), because it's very confusing if the // user tries to continue from this exception. if (TraceData.IsEnabled) { object styleSelector = d.ReadLocalValue(styleSelectorProperty); if (styleSelector != DependencyProperty.UnsetValue && (styleSelector is System.Windows.Controls.StyleSelector || styleSelector is ResourceReferenceExpression)) { object style = d.ReadLocalValue(styleProperty); if (style != DependencyProperty.UnsetValue && (style is Style || style is ResourceReferenceExpression)) { TraceData.Trace(TraceEventType.Error, TraceData.StyleAndStyleSelectorDefined(name), d); } } } }
private static void OnFocusBackgroundChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { if ( sender is FrameworkElement ) { var focusBehavior = GetFocusBehavior ( sender ); if ( e.NewValue == null ) { if ( focusBehavior != null ) { focusBehavior.Detach (); SetFocusBehavior ( sender, null ); } } else { if ( focusBehavior == null ) { focusBehavior = new ShowFocusBehavior (); focusBehavior.Attach ( sender as FrameworkElement ); SetFocusBehavior ( sender, focusBehavior ); if ( sender.ReadLocalValue ( PaddingProperty ) != DependencyProperty.UnsetValue ) { focusBehavior.Padding = GetPadding ( sender ); } } focusBehavior.FocusBackgroundBrush = GetFocusBackground ( sender ); } } }
/// <summary> /// Builds a path from an element to the root of its tree. Every /// element in between the element and the root is added to the /// path. /// </summary> /// <param name="node">the element to build a path for</param> /// <returns>the PathNode instance referring to the root of the tree; its /// children/descendants only include the nodes between the root and /// node</returns> private static PathNode BuildPathForElement(DependencyObject node) { Debug.Assert(node != null, "node can not be null"); PathNode childNode = null; while (node != null) { PathNode pathNode = new PathNode(node); if (childNode != null) pathNode.AddChild(childNode); childNode = pathNode; // If we find a node that has the service set on it, we should stop // after processing it. For cases without a service like unit tests, // this node won't be found and we'll continue to the root. if (node.ReadLocalValue(AnnotationService.ServiceProperty) != DependencyProperty.UnsetValue) break; node = PathNode.GetParent(node); } return childNode; }
/// <summary> Static modifier for ErrorTemplate property </summary> /// <exception cref="ArgumentNullException"> DependencyObject element cannot be null </exception> 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); }
/// <summary> /// Adds style information to the provided collection /// </summary> /// <param name="styles">The styles.</param> /// <param name="currentElement">The current element.</param> /// <param name="style">The style.</param> /// <param name="inheritedStyle">if set to <c>true</c> [inherited style].</param> private static void AddStyleInformation(IList<ControlStyleViewModel> styles, DependencyObject currentElement, Style style, bool inheritedStyle = false) { var appliedStyle = new ControlStyleViewModel { TargetType = style.TargetType.ToString(), Style = style, IsInheritedStyle = inheritedStyle }; styles.Insert(0, appliedStyle); foreach (Setter setter in style.Setters) { var newSetter = new ControlStyleViewModel {Property = setter.Property.OwnerType.Name + "." + setter.Property.Name, Setter = setter, DependencyObject = currentElement, DependencyProperty = setter.Property}; if (setter.Value == null) newSetter.Value = "{x:Null}"; else { var extension = setter.Value as DynamicResourceExtension; if (extension != null) newSetter.Value = "{DynamicResource " + extension.ResourceKey + "} = " + currentElement.GetValue(setter.Property); else newSetter.Value = setter.Value.ToString(); } appliedStyle.ControlStyles.Add(newSetter); } if (!inheritedStyle) { var local = currentElement.ReadLocalValue(FrameworkElement.StyleProperty); if (local != null) { var localType = local.GetType(); if (localType.Name == "ResourceReferenceExpression") { var resourceKeyProperty = localType.GetProperty("ResourceKey"); if (resourceKeyProperty != null) appliedStyle.Key = resourceKeyProperty.GetValue(local, null) as string; } } } if (style.BasedOn != null) AddStyleInformation(styles, currentElement, style.BasedOn, true); }
/// <summary> /// Check whether xxxTemplateSelector property is set on the given element. /// Only explicit local values or resource references count; data-bound or templated values don't count. /// </summary> internal static bool IsTemplateSelectorDefined(DependencyProperty templateSelectorProperty, DependencyObject d) { // Check whether xxxTemplateSelector property is set on the given element. object templateSelector = d.ReadLocalValue(templateSelectorProperty); // the checks for UnsetValue and null are for perf: // they're redundant to the type checks, but they're cheaper return (templateSelector != DependencyProperty.UnsetValue && templateSelector != null && (templateSelector is System.Windows.Controls.DataTemplateSelector || templateSelector is ResourceReferenceExpression)); }
private void PopulateProperties(DependencyObject currentElement, Type elementType, List<ControlPropertyViewModel> properties) { var fieldList = elementType.GetFields(BindingFlags.Static | BindingFlags.Public).ToList(); var fields = fieldList.Where(p => p.FieldType == typeof(DependencyProperty)); var resourceReferenceExpressionConverter = new ResourceReferenceExpressionConverter(); foreach (var field in fields) { var dependencyProperty = field.GetValue(currentElement) as DependencyProperty; if (dependencyProperty == null) continue; var currentValue = currentElement.GetValue(dependencyProperty); var isDefault = false; var isExtension = false; var resourceName = string.Empty; var isBound = false; var bindingExpression = string.Empty; if (currentValue != null) { isDefault = currentValue.Equals(dependencyProperty.DefaultMetadata.DefaultValue); try { var localValue = currentElement.ReadLocalValue(dependencyProperty); if (localValue.GetType().Name == "ResourceReferenceExpression") // Note: This is an internal type and hence it not visible to us as an actual type { var markupExtension = resourceReferenceExpressionConverter.ConvertTo(localValue, typeof (MarkupExtension)); var extension = markupExtension as DynamicResourceExtension; if (extension != null) { isExtension = true; resourceName = extension.ResourceKey.ToString(); } } } catch (ArgumentException) { } var binding = BindingOperations.GetBinding(currentElement, dependencyProperty); if (binding != null) { isBound = true; bindingExpression = binding.Path.Path; if (binding.Mode != BindingMode.Default) bindingExpression += ", Mode=" + binding.Mode.ToString(); if (!string.IsNullOrEmpty(binding.ElementName)) bindingExpression += ", ElementName=" + binding.ElementName; if (binding.RelativeSource != null) bindingExpression += ", RelativeSource={RelativeSource " + binding.RelativeSource.Mode + "}"; } } var newProp = new ControlPropertyViewModel { Name = field.Name, DependencyObject = currentElement, Value = currentValue, IsDefault = isDefault, IsResource = isExtension, ResourceName = resourceName, IsBound = isBound, BindingExpression = bindingExpression }; properties.Add(newProp); } if (elementType.BaseType != null) PopulateProperties(currentElement, elementType.BaseType, properties); }
/// <summary> /// Checks to see if the node has an annotation service set on it. /// This is a callback for DescendentsWalker and will be called for each logical /// and visual node at most once. /// We throw instead of returning a value in 'data' because we want to short-circuit /// the visiting of the rest of the tree and this method is currently only used /// for error-checking. /// </summary> /// <param name="node">the node to check for a service</param> /// <param name="data">this parameter is ignored</param> /// <returns>always returns true, to continue the traversal</returns> static private bool VerifyNoServiceOnNode(DependencyObject node, object data, bool visitedViaVisualTree) { Invariant.Assert(node != null, "Parameter 'node' is null."); // Check that there is no existing service for this node - we use the local value // because we don't want to get a false positive based on a service set further // up the tree. AnnotationService existingService = node.ReadLocalValue(AnnotationService.ServiceProperty) as AnnotationService; if (existingService != null) { throw new InvalidOperationException(SR.Get(SRID.AnnotationServiceAlreadyExists)); } return true; }
private static string readStringDPValue(DependencyObject d, DependencyProperty dp) { var value = d.ReadLocalValue(dp); return (value == DependencyProperty.UnsetValue ? string.Empty : value.ToString()); }