internal int FindZOrderIndex(StylusPlugInCollection spicAdding) { //should be called inside of lock(__rtiLock) DependencyObject spicAddingVisual = spicAdding.Element as Visual; int i; for (i = 0; i < _plugInCollectionList.Count; i++) { // first see if parent of node, if it is then we can just scan till we find the // first non parent and we're done DependencyObject curV = _plugInCollectionList[i].Element as Visual; if (VisualTreeHelper.IsAncestorOf(spicAddingVisual, curV)) { i++; while (i < _plugInCollectionList.Count) { curV = _plugInCollectionList[i].Element as Visual; if (!VisualTreeHelper.IsAncestorOf(spicAddingVisual, curV)) { break; // done } i++; } return(i); } else { // Look to see if spicAddingVisual is higher in ZOrder than i, if so then we're done DependencyObject commonParent = VisualTreeHelper.FindCommonAncestor(spicAddingVisual, curV); // If no common parent found then we must have multiple plugincollection elements // that have been removed from the visual tree and we haven't been notified yet of // that change. In this case just ignore this plugincollection element and go to // the next. if (commonParent == null) { continue; } // If curV is the commonParent we find then we're done. This new plugin should be // above this one. if (curV == commonParent) { return(i); } // now find first child for each under that common visual that these fall under (not they must be different or common parent is sort of busted. while (VisualTreeHelper.GetParentInternal(spicAddingVisual) != commonParent) { spicAddingVisual = VisualTreeHelper.GetParentInternal(spicAddingVisual); } while (VisualTreeHelper.GetParentInternal(curV) != commonParent) { curV = VisualTreeHelper.GetParentInternal(curV); } // now see which is higher in zorder int count = VisualTreeHelper.GetChildrenCount(commonParent); for (int j = 0; j < count; j++) { DependencyObject child = VisualTreeHelper.GetChild(commonParent, j); if (child == spicAddingVisual) { return(i); } else if (child == curV) { break; // look at next index in _piList. } } } } return(i); // this wasn't higher so return last index. }