2.2.5 ItemTemplate, ContentTemplate and DataTemplate
Before we understand the relationship between ItemTemplate, ContentTemplate and DataTemplate, let's take a look at the ContentControl class and the ItemsControl class. The ContentControl class is the base class for content controls, such as button, CheckBox, the most obvious feature is that the control has a content property, and the system control with the content property is a subclass of ContentControl. The ItemsControl class is the base class for a list content control, such as a ListBox, which is similar to the ContentControl class, except that the ContentControl class is a single item, and ItemsControl is a multi-item content.
Then all the ContentTemplate properties of the content controls that inherit from ContentControl and all the ItemTemplate properties of the list control that inherit from ItemsControl are of type DataTemplate, This means that we can use DataTemplate to define UI effects and data display for ContentControl and ItemsControl controls.
2.2.6 Use of data templates
DataTemplate is a visual data template that is powerful in the way that data can be presented to a control through binding. In the above example, we introduced the use of DataTemplate to implement the UI control of the display of the content, then in fact, datatemplate the most important role is not to replace the ControlTemplate style definition, Instead, the data source information for the control of the data is presented to the control through databinding.
Let's look at how the DataTemplate data binding works with a button control.
Code Listing 2-5: data Template (Source code: 2nd Chapter \examples_2_5)
(1) First define a person class that represents the type of the data entity, the code is as follows:
public class Person {public string LastName {get; set;} public string FirstName {get; set;} }
(2) design a datatemplate, and use this datatemplate as a resource, which is the same as the style resources, DataTemplate can also be used as a public resource for multiple controls to use. So the content of this template is to use the StackPanel control to arrange the information of the person object horizontally.
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
< Page.Resources> < datatemplate x:key= "Personnamedatatemplate" > <stackpanel orientation= "Horizontal" > <textblock text= "{Binding LastName}"/> <textblock text= ", "/> <textblock text= "{binding firstname}"/> </stackpanel> </ Datatemplate> </ page.resources>
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
(3) Create a button control that associates the ContentTemplate property with the template resource.
<button x:name= "Singlepersonbutton" contenttemplate= "{StaticResource personnamedatatemplate}"/>
(4) Create a Person object and assign a value to the content property of the button control.
Singlepersonbutton.content = new Person {FirstName = "Lee", LastName = "Terry"};
Finally we can see the button running effect 2.14, DataTemplate can bind the data object to achieve a more flexible universal powerful UI data display effect.
650) this.width=650; "src=" Http://images.cnitblog.com/i/152755/201406/021400291149097.png "/>
Figure 2.14 button for data template bindings
So here's an example of the application of DataTemplate on a ContentControl type of control, so let's look at the implementation of DataTemplate on the ItemsControl type of control, ContentControl and ItemsControl can also be used directly as controls, if we don't need a button or a ListBox for some of the advanced features of these controls, You can use ContentControl or ItemsControl controls directly.
(1) Define a ItemsControl control that associates the ItemTemplate property with the template resource.
<itemscontrol x:name= "ItemsControl" itemtemplate= "{StaticResource personnamedatatemplate}"/>
(2) Create a collection of person objects and assign values to the ItemsSource property of the ItemsControl control.
Persons.add (new person {FirstName = "lee2", LastName = "Terry2"});
Persons.add (new person {FirstName = "lee3", LastName = "Terry3"});
Persons.add (new person {FirstName = "lee4", LastName = "Terry4"});
Persons.add (new person {FirstName = "lee5", LastName = "Terry5"});
Itemscontrol.itemssource = Persons;
As you can see from the running effect 2.15, ItemsControl can show the data collection in the form of a list, but you will find that the function of the list implemented directly with ItemsControl is very limited and cannot be scrolled, then combine the ContentTemplate to refine this List of controls.
650) this.width=650; "src=" Http://images.cnitblog.com/i/152755/201406/021402018173642.png "/>
(3) Define a ItemsControl style, in fact, is to customize a ControlTemplate template to use as a template for ItemsControl control, then this template is a template for the presentation of content. We defined a ScrollViewer control on the ControlTemplate template and then used a StackPanel control inside it, the Itemspresenter control. The DataTemplate of the list is projected directly above the Itemspresenter control. We've set different border colors for both the ScrollViewer control and the StackPanel control, so it's clear how the relationship between controls works when you run it.
650) this.width=650; "alt=" Copy Code "src=" http://common.cnblogs.com/images/ Copycode.gif "/>
<style x:name= "Itemscontrolstyle" targettype= "ItemsControl" > <setter property= " Template "> < setter.value> <controltemplate targettype= "ItemsControl" > <scrollviewer borderbrush= "Red" BorderThickness= " 6 "> <StackPanel orientation= "Horizontal" bacKground= "Blue" > <border borderbrush= "Yellow" borderthickness= "3" > <ItemsPresenter /> </Border> </StackPanel> </scrollviewer> </ControlTemplate> </Setter.Value> </Setter> </Style>
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
(4) Add the Style property on ItemsControl to the styles defined above.
<itemscontrol x:name= "ItemsControl" itemtemplate= "{StaticResource personnamedatatemplate}" style= "{StaticResour Ce itemscontrolstyle} "/>
Figure 2.15 List of data template bindings
The running effect of the program is shown in 2.16.
650) this.width=650; "src=" Http://images.cnitblog.com/i/152755/201406/021403313649218.png "/>
Figure 2.16 Individual modules of a list control
2.2.7 reading and replacing data templates
For the system style, we can use the C # code to read out and then modify, to achieve the purpose of dynamic change theme. So the technology is always the same, for the control of the DataTemplate, we can also be read through the C # code, and then dynamically replaced, to achieve a richer and more flexible style display scheme. It is also possible to read and replace data templates in C # code by reading and assigning the ContentTemplate property.
This kind of read and replace data template in the list of controls will be more common, such as I want to implement a function, through a list to show a batch of data, the user hit a certain piece of data, the style of the data will be changed, indicating that the data is selected, The user can then cancel the selection of this data and continue to select multiple data. So this function is very common in the case of multiple selection of data. Let's implement one of these features.
Code Listing 2-6 : Dynamic change of Style (source code: 2nd Chapter \examples_2_6)
(1) Define 3 DataTemplate resources, one is unchecked, one is selected, and one is the default state, in fact the default state and unchecked state are the same, but because the default state of the data item style cannot be called again in C #. A tap event was added to all two templates, and the user captures the user's Click event. The data source collection is the same as the previous example.
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
< Page.Resources> <!-- Select the style of the data item--> <datatemplate x:key= " Datatemplateselectkey " x:name=" Datatemplateselectname "> <grid tapped= "Stackpanel_tap_1" background= "Red" > <TextBlock Text= "{binding lastname}" fontsize= " /> </Grid> </DataTemplate> <!--The default data item style, note that the default data item style cannot be called again in C #--> <datatemplate x:key= "Datatemplatedefaultkey" x:Name= " Datatemplatedefaultname "> <stackpanel orientation= "Horizontal" Tapped = " Stackpanel_tap_1 "> <textblock text= "{binding lastname}"/> <textblock text= ", "/> <textblock text= "{ Binding firstname} "/> </ stackpanel> </datatemplate> <!--the style--> <datatemplate for unchecked data items x:key= "Datatemplatenoselectkey" x:name= "Datatemplatenoselectname" > <stackpanel orientation= "Horizontal" tapped = "Stackpanel_tap_1" > <textblock text= "{ Binding lastname} "/> <textblock text= ", "/> <textblock text= "{binding firstname}"/> </StackPanel> </DataTemplate> </ Page.Resources> Omit several code //create ItemsControl controls to bind the data <itemscontrol x of the list: Name= "ListBox" itemtemplate= "{staticresource datatemplatedefaultkey }"/>
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
(2) Handle the Click event to determine the template of the current control and the re-assignment template. The datatemplate defined in XAML can be accessed through the Name property.
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
private void stackpanel_tap_1 (Object sender, tappedroutedeventargs e) { // Gets the ItemContainerGenerator property of the ItemsControl object // Determine the data object that is bound by the DataContext of the clicked control // Then get the current ContentPresenter object from the ItemContainerGenerator contentpresenter mycontentpresenter = (ContentPresenter) (ListBox. Itemcontainergenerator.containerfromitem ((Sender as panel). DataContext); // Determine whether the data template is selected or unchecked, and then assign a value if (MyContentPresenter.ContentTemplate.Equals (Datatemplateselectname) ) { //assigned non-checked status templates myContentPresenter.ContentTemplate = datatemplatenoselectname; } else { //Assignment selected Template myContentPresenter.ContentTemplate = dataTemplateSelectName; } }
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
Run the effect 2.17, when we click on the data item, the font will become larger, the background will become red, the click will become the original appearance.
650) this.width=650; "src=" Http://images.cnitblog.com/i/152755/201406/021406292249614.png "/>
Figure 2.17 Dynamic Change style
(3) One thing to note here is that if you use the ListBox control instead of the ItemsControl control, you need to look through the visual tree when you get the ContentPresenter object. The implementation of the code is as follows:
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
private void stackpanel_tap_1 (Object sender, tappedroutedeventargs e) { //gets to the object is ListBoxItem ListBoxItem myListBoxItem = ( ListBoxItem) (ListBox. Itemcontainergenerator.containerfromitem ((Sender as panel). DataContext)); // find ContentPresenter in ListBoxItem ContentPresenter myContentPresenter = Findvisualchild<contentpresenter> (Mylistboxitem); ......// Omit several code } //find elements of a type in a visual tree private Childitem findvisualchild<childitem> (Dependencyobject obj) where childitem : dependencyobject { for (int i = 0; i < Visualtreehelper.getchildrencount (obj); i++) { DependencyObject child = Visualtreehelper.getchild (obj, i); if (Child != null && child is childitem) return (ChildItem) child; else { childItem childOfChild = FindVisualChild<childItem> (child); if (childofchild != null) return childOfChild; } } return null; }
650) this.width=650; "alt=" Copy Code "src=" Http://common.cnblogs.com/images/copycode.gif "/>
This article comes from the deep understanding of Windows Phone 8.1 UI Control programming
Source code Download: Http://vdisk.weibo.com/s/zt_pyrfNHoezI
Welcome to follow my Weibo @wp forestry administration
WP8.1 Technology Group: 372552293
[Wp8.1ui Control Programming] Windows phone understands and applies itemtemplate, ContentTemplate, and DataTemplate