private DependencyObject FindAncestorOfType(Type type, int level, DependencyObject d, bool isTracing) { if (type == null) { if (TraceData.IsEnabled) TraceData.Trace(TraceEventType.Error, TraceData.RefAncestorTypeNotSpecified); return null; } if (level < 1) { if (TraceData.IsEnabled) TraceData.Trace(TraceEventType.Error, TraceData.RefAncestorLevelInvalid); return null; } // initialize search to start at the parent of the given DO FrameworkObject fo = new FrameworkObject(d); fo.Reset(fo.GetPreferVisualParent(true).DO); while (fo.DO != null) { if (isTracing) { TraceData.Trace(TraceEventType.Warning, TraceData.AncestorLookup( type.Name, TraceData.Identify(fo.DO))); } if (type.IsInstanceOfType(fo.DO)) // found it! { if (--level <= 0) break; } fo.Reset(fo.PreferVisualParent.DO); } return fo.DO; }
///<summary> /// Return the container that owns the given element. If itemsControl /// is not null, return a container that belongs to the given ItemsControl. /// If itemsControl is null, return the closest container belonging to /// any ItemsControl. Return null if no such container exists. ///</summary> public static DependencyObject ContainerFromElement(ItemsControl itemsControl, DependencyObject element) { if (element == null) throw new ArgumentNullException("element"); // if the element is itself the desired container, return it if (IsContainerForItemsControl(element, itemsControl)) { return element; } // start the tree walk at the element's parent FrameworkObject fo = new FrameworkObject(element); fo.Reset(fo.GetPreferVisualParent(true).DO); // walk up, stopping when we reach the desired container while (fo.DO != null) { if (IsContainerForItemsControl(fo.DO, itemsControl)) { break; } fo.Reset(fo.PreferVisualParent.DO); } return fo.DO; }