The relationship between DataTemplate and ControlTemplate of the WPF template template and the application of "two"

Source: Internet
Author: User
Tags xpath xunit

1. The relationship between DataTemplate and ControlTemplate

Having studied DataTemplate and ControlTemplate, you should have realized that the control is just the act and the carrier of the data, is an abstract concept, as to what it itself looks like (the internal structure of the control), What the data will look like (data display structure) is generated by template. The ControlTemplate that determines the appearance of the control, the DataTemplate that determines the appearance of the data, are the two property values of the control class's template and ContentTemplate


Any template, ultimately, will be on the control, the control is the object of the template control, also known as templated control. You may ask: DataTemplate's goal should be data, how can it be a control? The feeling of datatemplate is really applied to the data object, but a set of controls that are applied to the data object must have a carrier? This carrier is generally implemented on a object called ContentPresenter . The ContentPresenter class has only the ContentTemplate attribute and no template attribute, which proves that hosting a set of controls generated by DataTemplate is his specialized purpose.

at this point, we can see that the tree whose roots are generated by ControlTemplate is the target control of ControlTemplate, and this templated control's Template property value is a ControlTemplate instance. Similarly, the tree root of the control generated by DataTemplate is a ContentPresenter control, and the ContentTemplate property value of this templated control is the DataTemplate instance. Because the ContentPresenter control is a node on the ControlTemplate control tree, the DataTemplate control tree is a subtree inside the ControlTemplate.

Obviously, if the data object is assigned to the DataContext property of ContentPresenter, the control generated by DataTemplate will naturally find the data object and treat it as its own data source.

2. Application


2.1 Application 1

There are two ways to set the application target for the template, one to set the properties of the control template/contenttemplate/itemtemlate/celltemplate, Controls that do not want to apply a template are not set, and the other is a whole application that applies the template to a type of control or data.
Applying ControlTemplate to all controls requires a style, but the style cannot tag x:key, such as the following code:

<window x:class= "wpfapplication11.wnd11421" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml" title= "wnd11421" height= "$" width= "> <w" Indow. resources> <!--ControlTemplate function on all target controls, the Style cannot be labeled x:key--> <style targettype= "{x:type TextBox}" &            Gt <setter property= "template" > <Setter.Value> <!--using TemplateBinding, consistent with template targets --<controltemplate targettype= "{x:type TextBox}" > <border snapstod                                evicepixels= "True" background= "{TemplateBinding Background}" Borderbrush= "{TemplateBinding BorderBrush}" borderthickness= "{TemplateBinding borderthickn ESS} "cornerradius=" 5 "> <scrollviewer snapstodevicepixels= "{TeMplatebinding snapstodevicepixels} "></ScrollViewer> </Border> &lt ;/controltemplate> </Setter.Value> </Setter> <setter property= "Marg            In "value=" 5 "></Setter> <setter property=" BorderBrush "value=" Black "></Setter> <setter property= "Height" value= "></Setter> </Style> </Window.Resources> <stack panel> <TextBox></TextBox> <TextBox></TextBox> <textbox style= "{x:null} "></TextBox> </StackPanel></Window>
The style does not have a x:key tag, the default is to refer to all the x:type specified controls, and if you do not want to apply it, mark the style {x:null}. Operating effects such as:


2.2 Application 2


Applying DataTemplate to a data type is to set the DataType property of DataTemplate, and DataTemplate as a resource cannot be marked with x:key, such as the following code:

<window x:class= "wpfapplication11.wnd11422" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local= "Clr-namespace:wpfapplication11" Ti Tle= "wnd11422" height= "width=" > <Window.Resources> <!--datatemplate Action on a data type, using datatype, cannot Set x:key--> <datatemplate datatype= "{x:type local:unit}" > <Grid> &LT;STACKP Anel orientation= "Horizontal" > <Grid> <rectangle fill= "Red" width= "{                    Binding Price} "stroke=" Yellow "></Rectangle> <textblock text=" {Binding year} "/>                </Grid> <textblock text= "{Binding price}" ></TextBlock> </StackPanel> </Grid> </DataTemplate> </Window.Resources> &LT;STACKPANEL&G        T <listbox x:nAme= "_listbox" ></ListBox> <combobox x:name= "_combox" ></ComboBox> </stackpanel></wi Ndow>

The target data type of the DataTemplate in the code and the entry type of the ListBox are unit:

    <summary>//DataType//    </summary> public    class Unit    {public int price        {get; Set Public        string Year {get; set;}    }
Specify the data source:

    public partial class Wnd11422:window    {public        wnd11422 ()        {            InitializeComponent ();            list<unit> _listunit = new List<unit> ()            {                new unit () {price=100, year= "2001"},                new unit () { Price=120, Year= "2002"},                new unit () {price=140, year= "2003"},                new unit () {price=180, year= "2004"},                new Unit () {price=150, year= "2005"},                new Unit () {price=200, year= "2006"},            };            _listbox.itemssource = _listunit;            _combox.itemssource = _listunit;        }    }
At this point DataTemplate will automatically load onto all the unit type objects, even though I do not specify ItemTemplate for the listbox and Compbox, I will get the same effect:



2.3 Application 3


Most of the time the data is accessed in XML, and if the XML node is first converted to the CLR data type then the application of DataTemplate is troublesome. DataTemplate is smart, with the ability to directly use the XML data node as the target object-----Theelement name (the signature) in the XML data can be used as datatype, and the child nodes of the element and attribute can be accessed using XPath. The following code uses XmlDataProvider as the data source (which XPath points out must be a set of nodes), note the changes in the details, and the result is the same as applying 2:

<window x:class= "wpfapplication11.wnd11423" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml" title= "wnd11423" height= "$" width= "> <w" Indow. Resources> <!--element names in XML can be used as datatype--> <datatemplate datatype= "XUnit" > <grid&gt                ; <stackpanel orientation= "Horizontal" > <Grid> <rectangle fill= "Red "Width=" {Binding [email protected]} "stroke=" Yellow "></Rectangle> <textblock Text = "{Binding [email protected]}"/> </Grid> <textblock text= "{Binding [Email protected]} " ></TextBlock> </StackPanel> </Grid> </DataTemplate> &lt ;! --XPATH specifies a set of nodes--<xmldataprovider x:key= "ds" xpath= "Xunits/xunit" > <x:xdata> <xunits xmlns= "" > <xunit price= "[year=]" 2001 "></XUnit> <xunit price= "year=" 2002 "></XUnit> <xunit price=" year= "2003 "></XUnit> <xunit price=" year= "2004" ></XUnit> <xunit Pr                Ice= "Year=" "2005" ></XUnit> <xunit price= "$" year= "2006" ></XUnit> </XUnits> </x:XData> </XmlDataProvider> </Window.Resources> &LT;STACKP Anel> <!--xmldataprovider use binding--> <listbox x:name= "_listbox" itemssource= "{Binding source={s Taticresource ds}} "></ListBox> <combobox x:name=" _combox "itemssource=" {Binding Source={staticresource DS}} "></ComboBox> </StackPanel></Window>


2.4 Application 4


The advantage of XML is that it can easily represent hierarchical data, such as: Grade----class----group or main Menu---sub-menu----level three menu. At the same time, WPF prepares the TreeView and MenuItem controls to display hierarchical data. The template that is able to help hierarchical controls display hierarchical data is hierachicaldatatemplate. Here are some common examples of practical work:

It is worth mentioning that the role of Hierarchicaldatatemplate is not MenuItem content but its Header. If you listen to MenuItem's Click events, we can remove the XML data from the header of the MenuItem that was clicked.

<window x:class= "wpfapplication11.wnd11424" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml" title= "wnd11424" height= "+" width= "> <w" Indow. Resources> <!--grade Template--Event handler:

        private void Stackpanel_click (object sender, RoutedEventArgs e)        {            //head is XmlElement            XmlElement Xmlelem = ( E.originalsource as MenuItem). Header as XmlElement;            MessageBox.Show (xmlelem.attributes["Name"]. Value);        }



The relationship between DataTemplate and ControlTemplate of the WPF template template and the application of "two"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.