In the previous section, no datatype in datatemplate in Windows Phone (-), we mentioned that some features in Windows Phone are limited, such as datatype in datatemplate. In fact, not only datatype, but also the trigger in datatemplate are not supported. This article analyzes the actual code.
View the WPF statement:
<Window.Resources> <local:Company x:Key="dataCompany" /> <DataTemplate DataType="{x:Type local:User}" > <StackPanel Orientation="Horizontal" > <TextBlock Text="{Binding UserID}" x:Name="userid"/> <TextBlock Text=" Name: "/> <TextBlock Text="{Binding UserName}" /> </StackPanel> <DataTemplate.Triggers> <DataTrigger Binding="{Binding UserID}" Value="2"> <Setter TargetName="userid" Property="Foreground" Value="Red" /> </DataTrigger> </DataTemplate.Triggers> </DataTemplate> <local:Company x:Key="UserList" > <local:User UserID="1" UserName="pan" /> <local:User UserID="2" UserName="qiao" /> <local:User UserID="3" UserName="zhu" /> </local:Company></Window.Resources>
The ListBox binding code is as follows:
<ListBox Height = "193" horizontalalignment = "Left" margin = "49,81, 0, 0 "name =" listbox1 "verticalignment =" TOP "width =" 181 "itemssource =" {staticresource userlist} "/> we can see that the ListBox does not use itemtemplate to bind the datatemplate, the results are displayed as required.
Note: <datatemplate datatype = "{X: type local: User}"> the user class instead of the company class must be bound here. Otherwise, an error is displayed and only the class name is displayed.
Figure 1.
In Windows Phone, datatemplate does not have datatype or trigger attribute. OK. What if we want to enable automatic binding of the user class as an item of the items control like WPF? Do you have to define an X: Key for each datatemplate, and then bind each itemscrontrol?
First look at the datatemplate in Windows Phone:
<DataTemplate x:Key="listDataTemplate"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding UserID}" /> <TextBlock Text=" Name: "/> <TextBlock Text="{Binding UserName}" /> </StackPanel> </DataTemplate>
ListBox binding statement: --- the upper-level datacontext is bound here.
<ListBox ItemTemplate="{StaticResource listDataTemplate}" Height="296" HorizontalAlignment="Left" Margin="39,86,0,0" Name="listBox1" VerticalAlignment="Top" Width="251" ItemsSource="{Binding}" />
For how to bind Data Types in Windows Phone, see
Applying data templates dynamically by type in wp7by
Florin BADEA: in English, Badea provides detailed explanations and solutions.