1. 程式人生 > >WPF原始碼分析系列一:剖析WPF模板機制的內部實現(五)

WPF原始碼分析系列一:剖析WPF模板機制的內部實現(五)

(注:本文是《剖析WPF模板機制的內部實現》系列文章的最後一篇文章,檢視上一篇文章請點這裡)

上一篇文章我們討論了DataTemplate型別的兩個重要變數,ContentControl.ContentTemplate和ContentPresenter.ContentTemplate,這一篇將討論這個型別的另一個重要變數ItemsControl.ItemTemplate。

4.2)ItemsControl.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.ItemsSource(IEnumerable型別)列表的資料項。這個方法的主要工作是根據引數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類內部被多次呼叫,其中關鍵的一次是在其內部類Generator的GenerateNext()方法。此外這個方法關於引數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。另外值得一提的時:ListBox和ListView的預設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。)

 

(感謝閱讀,歡迎批評指正,轉載請註明出處)