WPF源代码分析系列一:剖析WPF模板机制的内部实现(五)

(注:本文是《剖析WPF模板机制的内部实现》系列文章的最后一篇文章,查看上一篇文章请点这里)

上一篇文章我们讨论了DataTemplate类型的两个重要变量,ContentControl.ContentTemplate和ContentPresenter.ContentTemplate,这一篇将讨论这个类型的另一个重要变量ItemsControl.ItemTemplate

4.2ItemsControl.ItemTemplate

我们都知道ItemsControl控件在WPF中的重要性,ItemsControl.ItemTemplate用的也非常多,那么其在模板应用中的角色是什么呢?要回答这个问题,我们先看其定义:

    public static readonly DependencyProperty ItemTemplateProperty =
                DependencyProperty.Register(
                        "ItemTemplate",
                        typeof(DataTemplate),
                        typeof(ItemsControl),
                        new FrameworkPropertyMetadata(
                                (DataTemplate) null,
                                OnItemTemplateChanged));

        /// <summary>
        ///     ItemTemplate is the template used to display each item.
        /// </summary>public DataTemplate ItemTemplate
        {
            get { return (DataTemplate) GetValue(ItemTemplateProperty); }
            set { SetValue(ItemTemplateProperty, value); }
        }

        private static void OnItemTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((ItemsControl) d).OnItemTemplateChanged((DataTemplate) e.OldValue, (DataTemplate) e.NewValue);
        }

        protected virtual void OnItemTemplateChanged(DataTemplate oldItemTemplate, DataTemplate newItemTemplate)
        {
            CheckTemplateSource();
 
            if (_itemContainerGenerator != null)
            {
                _itemContainerGenerator.Refresh();
            }
        }

 可以看到当ItemsControl.ItemTemplate改变时,会调用_itemContainerGenerator.Refresh()。这个方法的定义如下:

        // regenerate everything
        internal void Refresh()
        {
            OnRefresh();
        }

        // Called when the items collection is refreshed
        void OnRefresh()
        {
            ((IItemContainerGenerator)this).RemoveAll();

            // tell layout what happened
            if (ItemsChanged != null)
            {
                GeneratorPosition position = new GeneratorPosition(0, 0);
                ItemsChanged(this, new ItemsChangedEventArgs(NotifyCollectionChangedAction.Reset, position, 0, 0));
            }
        }

可见这个方法调用OnRefresh(),后者的主要工作是清空已经生成的元素,并触发ItemsChanged事件,通知所有监听者列表已经被重置。

查找ItemsControl.ItemTemplate的引用会发现一个值得注意的方法ItemsControl.PrepareContainerForItemOverride

//*********************ItemsControl*************************

/// <summary> /// Prepare the element to display the item. This may involve /// applying styles, setting bindings, etc. /// </summary> protected virtual void PrepareContainerForItemOverride(DependencyObject element, object item) { // Each type of "ItemContainer" element may require its own initialization. // We use explicit polymorphism via internal methods for this. // // Another way would be to define an interface IGeneratedItemContainer with // corresponding virtual "core" methods. Base classes (ContentControl, // ItemsControl, ContentPresenter) would implement the interface // and forward the work to subclasses via the "core" methods. // // While this is better from an OO point of view, and extends to // 3rd-party elements used as containers, it exposes more public API. // Management considers this undesirable, hence the following rather // inelegant code. HeaderedContentControl hcc; ContentControl cc; ContentPresenter cp; ItemsControl ic; HeaderedItemsControl hic; if ((hcc = element as HeaderedContentControl) != null) { hcc.PrepareHeaderedContentControl(item, ItemTemplate, ItemTemplateSelector, ItemStringFormat); } else if ((cc = element as ContentControl) != null) { cc.PrepareContentControl(item, ItemTemplate, ItemTemplateSelector, ItemStringFormat); } else if ((cp = element as ContentPresenter) != null) { cp.PrepareContentPresenter(item, ItemTemplate, ItemTemplateSelector, ItemStringFormat); } else if ((hic = element as HeaderedItemsControl) != null) { hic.PrepareHeaderedItemsControl(item, this); } else if ((ic = element as ItemsControl) != null) { if (ic != this) { ic.PrepareItemsControl(item, this); } } }

这个方法共两个参数,第一个参数element的作用是作为第二个参数item的容器(container),这个item实际就是ItemsControl.ItemsSourceIEnumerable类型)列表的数据项。这个方法的主要工作是根据参数element的类型,做一些准备工作:如HeaderedContentControl和HeaderedItemsControl会把ItemTemplate的值赋给HeaderTemplate,而ContentControl和ContentPresenter则会用它更新ContentTemplate。如果是element也是ItemsControl,这意味着一个ItemsControl的ItemTemplate里又嵌套了一个ItemsControl,这时就把父控件的ItemTemplate传递给子控件的ItemTemplate。

现在关键的问题是这里的参数element和item到底是怎么来的?要回答这个问题我们需要搞清楚ItemsControl.PrepareContainerForItemOverride()方法是怎么被调用的。查看引用可以发现ItemsControl.PrepareItemContainer()方法调用了这个方法,其代码如下:

//**************ItemsControl****************

/// <summary> /// Prepare the element to act as the ItemContainer for the corresponding item. /// </summary> void IGeneratorHost.PrepareItemContainer(DependencyObject container, object item) { // GroupItems are special - their information comes from a different place GroupItem groupItem = container as GroupItem; if (groupItem != null) { groupItem.PrepareItemContainer(item, this); return; } if (ShouldApplyItemContainerStyle(container, item)) { // apply the ItemContainer style (if any) ApplyItemContainerStyle(container, item); } // forward ItemTemplate, et al. PrepareContainerForItemOverride(container, item); .........此处省略**行代码 }

可以看到这个方法调首先会检查这个container是否GroupItem类型,如果不是则调用PrepareContainerForItemOverride(),并把container作为其第一参数。继续追踪这个方法的引用,我们会发现:ItemContainerGenerator类的PrepareItemContainer()调用了这个方法:

//*****************ItemContainerGenerator********************
        /// <summary>
        /// Prepare the given element to act as the container for the
        /// corresponding item.  This includes applying the container style,
        /// forwarding information from the host control (ItemTemplate, etc.),
        /// and other small adjustments.
        /// </summary>
        /// <remarks>
        /// This method must be called after the element has been added to the
        /// visual tree, so that resource references and inherited properties
        /// work correctly.
        /// </remarks>
        /// <param name="container"> The container to prepare.
        /// Normally this is the result of the previous call to GenerateNext.
        /// </param>
        void IItemContainerGenerator.PrepareItemContainer(DependencyObject container)
        {
            object item = container.ReadLocalValue(ItemForItemContainerProperty);
            Host.PrepareItemContainer(container, item);
        }

这个方法的注释讲的比较清楚:这个方法的作用是对这个containter做一些预处理工作,包括应用样式,“转交”(forward)一些来自宿主控件(我们这个例子是ItemsControl)的信息(例如ItemTemplate等)。为了让资源引用和依赖属性继承正常工作,这个container在被加入visual tree前必须调用这个方法。

这个方法的第一个语句告诉我们数据项item可以通过container读取ItemForItemContainerProperty的值获得。这个属性是附加属性,ItemContainerGenerator有一个静态方法LinkContainerToItem(),是专门用来为每个container设定(连接)这个属性的:

//*****************ItemContainerGenerator********************

// establish the link from the container to the corresponding item internal static void LinkContainerToItem(DependencyObject container, object item) { // always set the ItemForItemContainer property container.ClearValue(ItemForItemContainerProperty); container.SetValue(ItemForItemContainerProperty, item); // for non-direct items, set the DataContext property if (container != item) { container.SetValue(FrameworkElement.DataContextProperty, item); } }

这个方法在ItemContainerGenerator类内部被多次调用,其中关键的一次是在其内部类GeneratorGenerateNext()方法。此外这个方法关于参数container的注释也表明,这个container是通过调用GenerateNext()获得的。因此这个方法无疑是异常重要的,其代码如下:

//****************ItemContainerGenerator*******************

/// <summary> Generate UI for the next item or group</summary> public DependencyObject GenerateNext(bool stopAtRealized, out bool isNewlyRealized) { DependencyObject container = null; isNewlyRealized = false; while (container == null) { UnrealizedItemBlock uBlock = _cachedState.Block as UnrealizedItemBlock; IList items =_factory.ItemsInternal; int itemIndex = _cachedState.ItemIndex; int incr = (_direction == GeneratorDirection.Forward) ? +1 : -1; if (_cachedState.Block == _factory._itemMap) _done = true; // we've reached the end of the list if (uBlock == null && stopAtRealized) _done = true; if (!(0 <= itemIndex && itemIndex < items.Count)) _done = true; if (_done) { isNewlyRealized = false; return null; } object item = items[itemIndex]; if (uBlock != null) { // We don't have a realized container for this item. Try to use a recycled container // if possible, otherwise generate a new container. isNewlyRealized = true; CollectionViewGroup group = item as CollectionViewGroup; // DataGrid needs to generate DataGridRows for special items like NewItemPlaceHolder and when adding a new row. // Generate a new container for such cases. bool isNewItemPlaceHolderWhenGrouping = (_factory._generatesGroupItems && group == null); if (_factory._recyclableContainers.Count > 0 && !_factory.Host.IsItemItsOwnContainer(item) && !isNewItemPlaceHolderWhenGrouping) { container = _factory._recyclableContainers.Dequeue(); isNewlyRealized = false; } else { if (group == null || !_factory.IsGrouping) { // generate container for an item container = _factory.Host.GetContainerForItem(item); } else { // generate container for a group container = _factory.ContainerForGroup(group); } } // add the (item, container) to the current block if (container != null) { ItemContainerGenerator.LinkContainerToItem(container, item); _factory.Realize(uBlock, _cachedState.Offset, item, container); // set AlternationIndex on the container (and possibly others) _factory.SetAlternationIndex(_cachedState.Block, _cachedState.Offset, _direction); } } else { // return existing realized container isNewlyRealized = false; RealizedItemBlock rib = (RealizedItemBlock)_cachedState.Block; container = rib.ContainerAt(_cachedState.Offset); } // advance to the next item _cachedState.ItemIndex = itemIndex; if (_direction == GeneratorDirection.Forward) { _cachedState.Block.MoveForward(ref _cachedState, true); } else { _cachedState.Block.MoveBackward(ref _cachedState, true); } } return container; }

从代码可以看出,一个Generator在GenerateNext时,需要从_factory的ItemsInternal列表读取一个item,然后再调用_factory字段的Host属性的GetContainerForItem()方法来为这个item生成一个container。那么这个关键的_factory字段从何而来?事实上,_factory字段是ItemsContainerGenerator类型,另外ItemsContainerGenerator类内部有一个Generator类型的字段_generator,这个字段在创建对象时会将这个ItemsContainerGenerator自身作为参数,传给其_factory字段。

Generator.GenerateNext()方法一共被调用了两次,都是在两个被重载的ItemsContainerGenerator.GenerateNext()方法里:

        DependencyObject IItemContainerGenerator.GenerateNext()
        {
            bool isNewlyRealized;
            if (_generator == null)
                throw new InvalidOperationException(SR.Get(SRID.GenerationNotInProgress));

            return _generator.GenerateNext(true, out isNewlyRealized);
        }

        DependencyObject IItemContainerGenerator.GenerateNext(out bool isNewlyRealized)
        {
            if (_generator == null)
                throw new InvalidOperationException(SR.Get(SRID.GenerationNotInProgress));

            return _generator.GenerateNext(false, out isNewlyRealized);
        }

其中,第一个方法比较重要,它一共被调用了三次,其中两次是在Panel类:一次在Panel.GenerateChildren(),一次在Panel.AddChildren()。二者大同小异,我们只看第一个就足够了:

        internal virtual void GenerateChildren()
        {
            // This method is typically called during layout, which suspends the dispatcher.
            // Firing an assert causes an exception "Dispatcher processing has been suspended, but messages are still being processed."
            // Besides, the asserted condition can actually arise in practice, and the
            // code responds harmlessly.

            IItemContainerGenerator generator = (IItemContainerGenerator)_itemContainerGenerator;
            if (generator != null)
            {
                using (generator.StartAt(new GeneratorPosition(-1, 0), GeneratorDirection.Forward))
                {
                    UIElement child;
                    while ((child = generator.GenerateNext() as UIElement) != null)
                    {
                        _uiElementCollection.AddInternal(child);
                        generator.PrepareItemContainer(child);
                    }
                }
            }
        }

从代码可以看到,Panel会循环调用其_itemContainerGenerator字段(Generator属性)的GenerateNext()方法直到无法继续。每次调用都会生成一个UIElement类型的child,这个child将被加入Panel的内部UI元素列表,并对其调用_itemContainerGenerator.PrepareItemContainer(child)方法。而这里的这个child就是我们前面提到的container。

至此,container和item的来龙去脉我们算基本搞清楚了。

但是,这里的问题是,Panel类的这个神秘的_itemContainerGenerator字段是从哪里来的?一个Panel怎么会和ItemContainerGenerator扯上关系?秘密就在下面这个方法:

//*************Panel*************

private void ConnectToGenerator() { ItemsControl itemsOwner = ItemsControl.GetItemsOwner(this); if (itemsOwner == null) { // This can happen if IsItemsHost=true, but the panel is not nested in an ItemsControl throw new InvalidOperationException(SR.Get(SRID.Panel_ItemsControlNotFound)); } IItemContainerGenerator itemsOwnerGenerator = itemsOwner.ItemContainerGenerator; if (itemsOwnerGenerator != null) { _itemContainerGenerator = itemsOwnerGenerator.GetItemContainerGeneratorForPanel(this); if (_itemContainerGenerator != null) { _itemContainerGenerator.ItemsChanged += new ItemsChangedEventHandler(OnItemsChanged); ((IItemContainerGenerator)_itemContainerGenerator).RemoveAll(); } } }

 

可以看到,这个方法会先调用静态方法ItemsControl.GetItemsOwner()获得这个Panel所处的ItemsControl。这个方法的定义如下:

//****************ItemsControl******************* 

/// <summary> /// Returns the ItemsControl for which element is an ItemsHost. /// More precisely, if element is marked by setting IsItemsHost="true" /// in the style for an ItemsControl, or if element is a panel created /// by the ItemsPresenter for an ItemsControl, return that ItemsControl. /// Otherwise, return null. /// </summary> public static ItemsControl GetItemsOwner(DependencyObject element) { ItemsControl container = null; Panel panel = element as Panel; if (panel != null && panel.IsItemsHost) { // see if element was generated for an ItemsPresenter ItemsPresenter ip = ItemsPresenter.FromPanel(panel); if (ip != null) { // if so use the element whose style begat the ItemsPresenter container = ip.Owner; } else { // otherwise use element's templated parent container = panel.TemplatedParent as ItemsControl; } } return container;
}

这个方法的逻辑很简单:在获取一个Panel所关联的ItemsControl时,如果这个Panel的IsItemsHost属性非真则返回空值;不然,那么如果这个Panel的TemplateParent是ItemsPresenter,则返回其Owner,否则则直接返回这个Panel的TemplateParent。

在知道自己所在的ItemsControl后,这个Panel就能调用这个ItemsControl的ItemContainerGenerator属性的GetItemContainerGeneratorForPanel()方法来获得一个正确的ItemContainerGenerator给其_itemContainerGenerator字段(Panel的Generator属性)赋值。

现在问题的关键是,一个Panel的TemplateParent是怎么和一个ItemsControl扯上关系的?我们在第三篇文章介绍ItemsPanelTemplate时曾提到过,ItemsControl的默认Template里的ItemsPresenter只起一个占位符(placeholder)的作用,它的主要角色是接收ItemsControl的ItemsPanel模板,并在ItemsControl应用模板时应用这个模板。

我们再可以看一下ItemsControl的默认ItemsPanel模板:

        <ItemsPanelTemplate x:Key="ItemsPanelTemplate1">
            <StackPanel/>
        </ItemsPanelTemplate>

 (我们前面提到过,ItemsControl类在注册ItemsPanelTemplateProperty依赖属性时,其默认值就是StackPanel。另外值得一提的时:ListBoxListView的默认ItemsPanel都是VirtualizingStackPanel,Menu类是WrapPanel,StatusBar类是DockPanel)。

而我们知道,要想让这个ItemsPanel模板起作用,ItemsControl的Template内还必须包含一个ItemsPresenter:

        <Style TargetType="{x:Type ItemsControl}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ItemsControl}">
                        <Border>
                            <ItemsPresenter />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

这时一个ItemsControl的Template模板里的ItemsPresenter在应用这个ItemsControl的ItemsPanel模板时,会将模板里面的Panel类控件的TemplateParent设定为这个ItemsControl,同时将其IsItemsHost属性标识为true。

ItemsControl还有一种用法是忽略ItemsPanel,直接在其Template内指定一个"ItemsPanel",如下面的代码:

        <Style TargetType="{x:Type ItemsControl}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ItemsControl}">
                        <Border>
                           <StackPanel IsItemsHost="True"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

这时ItemsPanel模板的设置将被直接忽略。不过,这时一定要将这个Panel的IsItemsHost设定为True,否则ItemsControl将找不到一个合适的ItemsPanel来显示列表项。

最后,结合第三篇文章的内容,我们再按照从上至下的顺序从整体上梳理一下ItemsControl的模板应用机制:一个ItemsControl在应用模板时,首先会应用Template模板(ControlTemplate类型)生成自身的visual tree(Control类的模板机制),然后Template模板中的ItemsPresenter应用其TemplateParent(即这个ItemsControl)的ItemsPanel模板(ItemsPanelTemplate类型)生成一个visual tree,并把这个visual tree放置在这个ItemsPresenter的位置(ItemsPresenter这时起到占位符的作用)。在ItemsPanel模板被应用时,这个面板的TemplateParent会被指向这个ItemsControl,同时其IsItemsHost属性被标识为true。ItemsControl的ItemContainerGeneror在遍历自己的ItemsInternal列表并为每个列表项(item)生成一个container,并将ItemsControl的ItemTemplate模板“转交”(forward)给这个container,这样这个container就可以应用模板,为与自己对应的数据项(item)生成一个由这个ItemTemplate定义的visual tree。当然具体过程要复杂的多。

 

至此,本文算全部写完了。最后再强行总结一下WPF的模板机制:

1.FrameworkTemplate是所有模板类的基类,FrameworkElement类有一个FrameworkTemplate类型的TemplateInternal属性,FrameworkElement.ApplyTemplate()将使用这个属性的模板对象来生成visual tree,并将这个visual tree赋值给自己的TemplateChild属性,从而在两个Visual类对象之间建立起parent-child relationship;

2.FrameworkElement的TemplateInternal属性是虚属性,FrameworkElement子类可以通过覆写这个属性来自定义模板。只有四个类Control、ContentPresenter、ItemsPresenter、Page覆写了这个属性,这意味着只有这4个类及其子类控件才能应用自定义的模板,它们也是WPF模板机制的实现基础;

3.FrameworkTemplate类有三个子类:ControlTemplate、ItemsPanelTemplate和DataTemplate。WPF中这些模板类定义的变量很多,它们的内部实现也不尽相同,不过万变不离其宗,所有模板类最终都要把自己传递到FrameworkElement.TemplateInternal属性上,才能被应用,生成的visual tree才能被加载到整体的visual tree中。FrameworkElement.ApplyTemplate()方法是FrameworkElement及其子类模板应用的总入口。

  

(WPF源代码:https://github.com/dotnet/wpf。)

 

(感谢阅读,欢迎批评指正,转载请注明出处)

 

 

posted @ 2020-12-18 12:02  至简之道  阅读(1255)  评论(2编辑  收藏  举报