//+----------------------------------------------------------------------------------
        //
        //  ApplyTemplateContent
        //
        //  Instantiate the content of the template (either from FEFs or from Baml).
        //  This is done for every element to which this template is attached.
        //
        //+----------------------------------------------------------------------------------
        #region InstantiateSubTree

        //[CodeAnalysis("AptcaMethodsShouldOnlyCallAptcaMethods")] //Tracking Bug: 29647
        internal static bool ApplyTemplateContent(
            UncommonField<HybridDictionary[]>  dataField,
            DependencyObject            container,
            FrameworkElementFactory     templateRoot,
            int                         lastChildIndex,
            HybridDictionary            childIndexFromChildID,
            FrameworkTemplate           frameworkTemplate)
        {
            Debug.Assert(frameworkTemplate != null );

            bool visualsCreated = false;

            FrameworkElement feContainer = container as FrameworkElement;

            // Is this a FEF-style template?

            if (templateRoot != null)
            {
                // Yes, we'll instantiate from a FEF tree.

                EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose, EventTrace.Event.WClientParseInstVisTreeBegin);

                CheckForCircularReferencesInTemplateTree(container, frameworkTemplate );

                // Container is considered ChildIndex '0' (Self), but,
                // Container.ChildIndex isn't set
                List<DependencyObject> affectedChildren = new List<DependencyObject>(lastChildIndex);

                // Assign affectedChildren to container
                TemplatedFeChildrenField.SetValue(container, affectedChildren);

                // When building the template children chain, we keep a chain of
                // nodes that don't need to be in the chain for property invalidation
                // or lookup purposes.  (And hence not assigned a TemplateChildIndex)
                // We only need them in order to clean up their _templatedParent
                // references (see FrameworkElement.ClearTemplateChain)
                List<DependencyObject> noChildIndexChildren = null;

                // Instantiate template
                // Setup container's reference to first child in chain
                // and add to tree
                DependencyObject treeRoot = templateRoot.InstantiateTree(
                    dataField,
                    container,
                    container,
                    affectedChildren,
                    ref noChildIndexChildren,
                    ref frameworkTemplate.ResourceDependents);

                Debug.Assert(treeRoot is FrameworkElement || treeRoot is FrameworkContentElement,
                    "Root node of tree must be a FrameworkElement or FrameworkContentElement.  This should have been caught by set_VisualTree" );

                // From childFirst to childLast is the chain of child nodes with
                //  childIndex.  Append that chain with the chain of child nodes
                //  with no childIndex assigned.
                if( noChildIndexChildren != null )
                {
                    affectedChildren.AddRange(noChildIndexChildren);
                }

                visualsCreated = true;

                if (feContainer != null && EventTrace.IsEnabled(EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose))
                {
                    string label = feContainer.Name;
                    if (label == null || label.Length == 0)
                        label = container.GetHashCode().ToString(System.Globalization.CultureInfo.InvariantCulture);

                    EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientParseInstVisTreeEnd, EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose,
                                                         String.Format(System.Globalization.CultureInfo.InvariantCulture, "Style.InstantiateSubTree for {0} {1}", container.GetType().Name, label));
                }
            }

            // It's not a FEF-style template, is it a non-empty optimized one?

            else if (frameworkTemplate != null && frameworkTemplate.HasXamlNodeContent)
            {
                // Yes, create from the optimized template content.
                EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose, EventTrace.Event.WClientParseInstVisTreeBegin);

                CheckForCircularReferencesInTemplateTree(container, frameworkTemplate );

                // Container is considered ChildIndex '0' (Self), but,
                // Container.ChildIndex isn't set

                List<DependencyObject> affectedChildren = new List<DependencyObject>(lastChildIndex);

                // Assign affectedChildren to container

                TemplatedFeChildrenField.SetValue(container, affectedChildren);

                DependencyObject treeRoot;

                // Load the content

                treeRoot = frameworkTemplate.LoadContent( container, affectedChildren);

                Debug.Assert(treeRoot == null || treeRoot is FrameworkElement || treeRoot is FrameworkContentElement,
                    "Root node of tree must be a FrameworkElement or FrameworkContentElement.  This should have been caught by set_VisualTree" );

                visualsCreated = true;

                if (feContainer != null && EventTrace.IsEnabled(EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose))
                {
                    string label = feContainer.Name;
                    if (label == null || label.Length == 0)
                        label = container.GetHashCode().ToString(System.Globalization.CultureInfo.InvariantCulture);

                    EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientParseInstVisTreeEnd, EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose,
                                                         String.Format(System.Globalization.CultureInfo.InvariantCulture, "Style.InstantiateSubTree for {0} {1}", container.GetType().Name, label));
                }
            }

            // No template was supplied.  Allow subclasses to provide the template.
            // This is currently only implemented for FrameworkElement's.

            else
            {
                if (feContainer != null)
                {
                    // This template will not be driven by the Style in any way.
                    // Rather, it will be built and initialized by the callee

                    // CALLBACK
#if DEBUG
                    Debug.Assert( feContainer._buildVisualTreeVerification == VerificationState.WaitingForBuildVisualTree,
                        "The BuildVisualTree override has triggered another call to itself.  This is not good - something between the two Style.InstantiateSubTree calls on the stack is doing A Very Bad Thing.");
                    feContainer._buildVisualTreeVerification = VerificationState.WaitingForAddCustomTemplateRoot;
                    bool exceptionThrown = true;
                    try
                    {
#endif

                    Debug.Assert(frameworkTemplate != null, "Only FrameworkTemplate has the ability to build a VisualTree by this means");
                    visualsCreated = frameworkTemplate.BuildVisualTree(feContainer);

#if DEBUG
                    exceptionThrown = false;
                    }
                    finally
                    {
                        if (!exceptionThrown)   // results are unreliable if an exception was thrown
                        {
                            if( visualsCreated )
                            {
                                Debug.Assert( feContainer._buildVisualTreeVerification == VerificationState.WaitingForBuildVisualTreeCompletion,
                                    "A derived class overriding BuildVisualTree must call AddCustomTemplateRoot to attach its custom subtree before exiting.");
                            }
                            else
                            {
                                Debug.Assert( feContainer._buildVisualTreeVerification == VerificationState.WaitingForAddCustomTemplateRoot,
                                    "If a derived class overriding BuildVisualTree has called AddCustomTemplateRoot to attach its custom subtree, its BuildVisualTree must return true to indicate that it has done so.");
                            }
                        }

                        // All done building this visual tree, stand by for the next one.
                        feContainer._buildVisualTreeVerification = VerificationState.WaitingForBuildVisualTree;
                    }
#endif
                }
            }

            return visualsCreated;
        }
        // Token: 0x06000691 RID: 1681 RVA: 0x00014908 File Offset: 0x00012B08
        internal DependencyObject InstantiateTree(UncommonField <HybridDictionary[]> dataField, DependencyObject container, DependencyObject parent, List <DependencyObject> affectedChildren, ref List <DependencyObject> noChildIndexChildren, ref FrugalStructList <ChildPropertyDependent> resourceDependents)
        {
            EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose, EventTrace.Event.WClientParseFefCrInstBegin);
            FrameworkElement frameworkElement = container as FrameworkElement;
            bool             flag             = frameworkElement != null;
            DependencyObject dependencyObject = null;

            if (this._text != null)
            {
                IAddChild addChild = parent as IAddChild;
                if (addChild == null)
                {
                    throw new InvalidOperationException(SR.Get("TypeMustImplementIAddChild", new object[]
                    {
                        parent.GetType().Name
                    }));
                }
                addChild.AddText(this._text);
            }
            else
            {
                dependencyObject = this.CreateDependencyObject();
                EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose, EventTrace.Event.WClientParseFefCrInstEnd);
                FrameworkObject frameworkObject = new FrameworkObject(dependencyObject);
                Visual3D        visual3D        = null;
                bool            flag2           = false;
                if (!frameworkObject.IsValid)
                {
                    visual3D = (dependencyObject as Visual3D);
                    if (visual3D != null)
                    {
                        flag2 = true;
                    }
                }
                bool isFE = frameworkObject.IsFE;
                if (!flag2)
                {
                    FrameworkElementFactory.NewNodeBeginInit(isFE, frameworkObject.FE, frameworkObject.FCE);
                    if (StyleHelper.HasResourceDependentsForChild(this._childIndex, ref resourceDependents))
                    {
                        frameworkObject.HasResourceReference = true;
                    }
                    FrameworkElementFactory.UpdateChildChains(this._childName, this._childIndex, isFE, frameworkObject.FE, frameworkObject.FCE, affectedChildren, ref noChildIndexChildren);
                    FrameworkElementFactory.NewNodeStyledParentProperty(container, flag, isFE, frameworkObject.FE, frameworkObject.FCE);
                    if (this._childIndex != -1)
                    {
                        StyleHelper.CreateInstanceDataForChild(dataField, container, dependencyObject, this._childIndex, this._frameworkTemplate.HasInstanceValues, ref this._frameworkTemplate.ChildRecordFromChildIndex);
                    }
                    if (this.HasLoadedChangeHandler)
                    {
                        BroadcastEventHelper.AddHasLoadedChangeHandlerFlagInAncestry(dependencyObject);
                    }
                }
                else if (this._childName != null)
                {
                    affectedChildren.Add(dependencyObject);
                }
                else
                {
                    if (noChildIndexChildren == null)
                    {
                        noChildIndexChildren = new List <DependencyObject>(4);
                    }
                    noChildIndexChildren.Add(dependencyObject);
                }
                if (container == parent)
                {
                    TemplateNameScope value = new TemplateNameScope(container);
                    NameScope.SetNameScope(dependencyObject, value);
                    if (flag)
                    {
                        frameworkElement.TemplateChild = frameworkObject.FE;
                    }
                    else
                    {
                        FrameworkElementFactory.AddNodeToLogicalTree((FrameworkContentElement)parent, this._type, isFE, frameworkObject.FE, frameworkObject.FCE);
                    }
                }
                else
                {
                    this.AddNodeToParent(parent, frameworkObject);
                }
                if (!flag2)
                {
                    StyleHelper.InvalidatePropertiesOnTemplateNode(container, frameworkObject, this._childIndex, ref this._frameworkTemplate.ChildRecordFromChildIndex, false, this);
                }
                else
                {
                    for (int i = 0; i < this.PropertyValues.Count; i++)
                    {
                        if (this.PropertyValues[i].ValueType != PropertyValueType.Set)
                        {
                            throw new NotSupportedException(SR.Get("Template3DValueOnly", new object[]
                            {
                                this.PropertyValues[i].Property
                            }));
                        }
                        object    obj       = this.PropertyValues[i].ValueInternal;
                        Freezable freezable = obj as Freezable;
                        if (freezable != null && !freezable.CanFreeze)
                        {
                            obj = freezable.Clone();
                        }
                        MarkupExtension markupExtension = obj as MarkupExtension;
                        if (markupExtension != null)
                        {
                            ProvideValueServiceProvider provideValueServiceProvider = new ProvideValueServiceProvider();
                            provideValueServiceProvider.SetData(visual3D, this.PropertyValues[i].Property);
                            obj = markupExtension.ProvideValue(provideValueServiceProvider);
                        }
                        visual3D.SetValue(this.PropertyValues[i].Property, obj);
                    }
                }
                for (FrameworkElementFactory frameworkElementFactory = this._firstChild; frameworkElementFactory != null; frameworkElementFactory = frameworkElementFactory._nextSibling)
                {
                    frameworkElementFactory.InstantiateTree(dataField, container, dependencyObject, affectedChildren, ref noChildIndexChildren, ref resourceDependents);
                }
                if (!flag2)
                {
                    FrameworkElementFactory.NewNodeEndInit(isFE, frameworkObject.FE, frameworkObject.FCE);
                }
            }
            return(dependencyObject);
        }