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

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

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

4. DataTemplate

上一篇文章我們討論了ItemsPanelTemplate類,這一篇和下一篇將討論DataTemplate類。

DataTemplate型別的變數非常多,主要有:

ComboBox.SelectionBoxItemTemplate

ContentControl.ContentTemplate

ContentPresenter.ContentTemplate

ContentPresenter.Template

DataGrid.RowHeaderTemplate

DataGridColumn.HeaderTemplate

DataGridRow.HeaderTemplate

DataGridRow.DetailsTemplate

DataGridTemplateColumn.CellTemplate

DataGridTemplateColumn.CellEditingTemplate

GridView.ColumnHeaderTemplate

GridViewColumn.HeaderTemplate

GridViewColumn.CellTemplate

GridViewHeaderRowPresenter.ColumnHeaderTemplate

GroupStyle.HeaderTemplate

HeaderedContentControl.HeaderTemplate

HeaderedItemsControl.HeaderTemplate

HierarchicalDataTemplate.ItemTemplate

ItemsControl.ItemTemplate

TabControl.SelectedContentTemplate

TabControl.ContentTemplate

我們這裡只重點分析比較重要和有代表性的三個:ContentControl.ContentTemplate,ContentPresenter.ContentTemplate和ItemsControl.ItemTemplate。本篇文章只討論前兩個,ItemsControl.ItemTemplate

留待下一篇文章討論。

4.1ContentControl.ContentTemplateContentPresenter.ContentTemplate

ContentControl和ContentPresenter的父類分別是Control和FrameworkElement,這意味著ContentControl也繼承了Control.Template屬性和模板選擇機制。那麼ContentControl.ContentTemplate屬性和其Template屬性究竟有什麼關係?ContentControl和ContentPresenter的ContentTemplate屬性在模板應用的角色是什麼,二者又有什麼聯絡?

要回答這些問題,我們先看ContentPresenter.ContentTemplate的定義:

//************ContentPresenter.cs**************public static readonly DependencyProperty ContentTemplateProperty =
                ContentControl.ContentTemplateProperty.AddOwner(
                        typeof(ContentPresenter),
                        new FrameworkPropertyMetadata(
                                (DataTemplate)null,
                                FrameworkPropertyMetadataOptions.AffectsMeasure,
                                new PropertyChangedCallback(OnContentTemplateChanged)));

 

        /// <summary>
        ///     ContentTemplate is the template used to display the content of the control.
        /// </summary>
        public DataTemplate ContentTemplate
        {
            get { return (DataTemplate) GetValue(ContentControl.ContentTemplateProperty); }
            set { SetValue(ContentControl.ContentTemplateProperty, value); }
        }

        private static void OnContentTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ContentPresenter ctrl = (ContentPresenter)d;
            ctrl._templateIsCurrent = false;
            ctrl.OnContentTemplateChanged((DataTemplate) e.OldValue, (DataTemplate) e.NewValue);
        }


        protected virtual void OnContentTemplateChanged(DataTemplate oldContentTemplate, DataTemplate newContentTemplate)
        {
            Helper.CheckTemplateAndTemplateSelector("Content", ContentTemplateProperty, ContentTemplateSelectorProperty, this);

            // if ContentTemplate is really changing, remove the old template
            this.Template = null;
        }

首先可以注意到依賴屬性ContentTemplateProperty的註冊沒有使用DependencyProperty.Register(),而是用的ContentControl.ContentTemplateProperty.AddOwner(),此外ContentTemplate的讀寫也是用的ContentControl.ContentTemplateProperty。這意味著如果ContentPresenter處在ContentControlContent的visual tree上,那麼其ContentTemplateProperty屬性將繼承ContentControl.ContentTemplateProperty的值。這就是WPF中依賴屬性的繼承。利用同樣的方法,ContentPresenter還繼承了ContentControl.ContentProperty屬性。而我們還知道,就像ItemsControl的預設Template會包含一個ItemsPresenter控制元件(參見上一篇文章),ContentControl的預設Template模板也包含一個ContentPresenter控制元件。這意味著當ContentControl在應用模板生成visual tree時,將建立一個ContentPresenter控制元件,並把自己的ContentTemplate和Content屬性的值傳遞給它的ContentPresenter控制元件,進而觸發其呼叫自己的ApplyTemplate。ContentControl(以及ItemsPresenter)的模板應用就是這樣一個大概可以分為兩個步驟的級聯過程。

ContentControl的模板應用機制這樣基本就清楚了,不過為了搞清楚這個級聯過程的第二個步驟,我們需要進一步剖析一下ContentPresenter的模板應用機制。

首先,從回撥函式可以看出,一旦ContentPresenter.ContentTemplate屬性被改變,無論這種任何變化,ContentPresenter.Template屬性都將被清空。這個屬性的定義如下:

//***********ContentPresenter.cs**************


        internal static readonly DependencyProperty TemplateProperty =
                DependencyProperty.Register(
                        "Template",
                        typeof(DataTemplate),
                        typeof(ContentPresenter),
                        new FrameworkPropertyMetadata(
                                (DataTemplate) null,  // default value
                                FrameworkPropertyMetadataOptions.AffectsMeasure,
                                new PropertyChangedCallback(OnTemplateChanged)));


        private DataTemplate Template
        {
            get {  return _templateCache; }
            set { SetValue(TemplateProperty, value); }
        }

        // Internal helper so FrameworkElement could see call the template changed virtual
        internal override void OnTemplateChangedInternal(FrameworkTemplate oldTemplate, FrameworkTemplate newTemplate)
        {
            OnTemplateChanged((DataTemplate)oldTemplate, (DataTemplate)newTemplate);
        }

        private static void OnTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ContentPresenter c = (ContentPresenter) d;
            StyleHelper.UpdateTemplateCache(c, (FrameworkTemplate) e.OldValue, (FrameworkTemplate) e.NewValue, TemplateProperty);
        }

這裡可以看到,ContentPresenter.Template與Control.Template、ItemsPresenter的定義如出一轍,都以_templateCache欄位作為支撐欄位,只不過Template的型別這次被換成了DataTemplate。不過與ItemsPresenter相同,ContentPresenter類也覆寫了FrameworkElement.OnPreApplyTemplate()方法,自定義了一個模板選擇機制。這個方法先是呼叫EnsureTemplate(),而後者接著又呼叫了ChooseTemplate()來根據一定的優先順序來選擇一個合適的DataTemplate,並用這個確定是非空的模板更新其Template屬性進而_templateCache欄位,從而保證Framework在呼叫ApplyTemplate()時TemplateInternal是非空的。

這裡有必要貼一下ContentPresenter.ChooseTemplate()方法的原始碼,看一下ContentPresenter選擇模板的優先順序:

//***********ContentPresenter**************

 

        /// <summary>
        /// Return the template to use.  This may depend on the Content, or
        /// other properties.
        /// </summary>
        /// <remarks>
        /// The base class implements the following rules:
        ///   (a) If ContentTemplate is set, use it.
        ///   (b) If ContentTemplateSelector is set, call its
        ///         SelectTemplate method.  If the result is not null, use it.
        ///   (c) Look for a DataTemplate whose DataType matches the
        ///         Content among the resources known to the ContentPresenter
        ///         (including application, theme, and system resources).
        ///         If one is found, use it.
        ///   (d) If the type of Content is "common", use a standard template.
        ///         The common types are String, XmlNode, UIElement.
        ///   (e) Otherwise, use a default template that essentially converts
        ///         Content to a string and displays it in a TextBlock.
        /// Derived classes can override these rules and implement their own.
        /// </remarks>
        protected virtual DataTemplate ChooseTemplate()
        {
            DataTemplate template = null;
            object content = Content;
 

            // ContentTemplate has first stab
            template = ContentTemplate;

            // no ContentTemplate set, try ContentTemplateSelector
            if (template == null)
            {
                if (ContentTemplateSelector != null)
                {
                    template = ContentTemplateSelector.SelectTemplate(content, this);
                }
            }

            // if that failed, try the default TemplateSelector
            if (template == null)
            {
                template = DefaultTemplateSelector.SelectTemplate(content, this);
            }

            return template;
        }

可以看出,ContentPresenter在選擇Template時,會優先選擇ContentTemplate,如果為空,則會嘗試呼叫ContentTemplateSelector.SelectTemplate()(DataTemplateSelector型別),如果再失敗,會嘗試呼叫其DefaultTemplateSelector.SelectTemplate()方法。

靜態屬性DefaultTemplateSelector是DefaultSelector型別 ,後者又繼承自DataTemplateSelector類。DefaultSelector在覆寫DataTemplateSelector.SelectTemplate()方法時引入了一套複雜的模板選擇規則,以確保最終可以返回一個有效的DataTemplate:

//*******************DefaultSelector***********************

            /// <summary>
            /// Override this method to return an app specific <seealso cref="Template"/>.
            /// </summary>
            /// <param name="item">The data content</param>
            /// <param name="container">The container in which the content is to be displayed</param>
            /// <returns>a app specific template to apply.</returns>
            public override DataTemplate SelectTemplate(object item, DependencyObject container)
            {

                DataTemplate template = null;

                // Lookup template for typeof(Content) in resource dictionaries.
                if (item != null)
                {
                    template = (DataTemplate)FrameworkElement.FindTemplateResourceInternal(container, item, typeof(DataTemplate));
                }

                // default templates for well known types:
                if (template == null)
                {
                    TypeConverter tc = null;
                    string s;
 
                    if ((s = item as string) != null)
                        template = ((ContentPresenter)container).SelectTemplateForString(s);
                    else if (item is UIElement)
                        template = UIElementContentTemplate;
                    else if (SystemXmlHelper.IsXmlNode(item))
                        template = ((ContentPresenter)container).SelectTemplateForXML();
                    else if (item is Inline)
                        template = DefaultContentTemplate;
                    else if (item != null &&
                                (tc = TypeDescriptor.GetConverter(ReflectionHelper.GetReflectionType(item))) != null &&
                                tc.CanConvertTo(typeof(UIElement)))
                        template = UIElementContentTemplate;
                    else
                        template = DefaultContentTemplate;
                }

                return template;
            }
        }

至此,ContentPresenter在模板應用中的角色也一目瞭然了。可以看到ContentPresenter和ItemsPresenter的模板應用機制大同小異,它們都定義了一個_templateCache欄位,並都覆寫了FrameworkElement.TemplateInternal屬性,使其返回值為_templateCache欄位,同時又都覆寫FrameworkElement.OnPreApplyTemplate()方法,來嵌入一個自定義的模板選擇機制,並用選定的模板更新_templateCache欄位。於是,它們利用這種模式實現了FrameworkElement.TemplateInternal屬性的多型性,從而變相實現了FrameworkElement.ApplyTemplate()的多型性。

至此,兩個重要的DataTemplate型別ContentControl.ContentTemplate和ContentPresenter.ContentTemplate就介紹了完畢,下一篇文章將介紹DataTemplate型別的另一個重要變數ItemsControl.ItemTemplate。