Adding a DataTemplate to the global resource dictionary

Now let's get back to the App.xaml file. Since we require a custom cell in our ListView on the StocklistPage, we are going to create a DataTemplate in the global resource dictionary. DataTemplate can be created in two ways, as an inline template or in a resource dictionary. There is no better method, it's more on personal preference. In our example, we are going to be creating ours in a resource dictionary.

Open up the App.xaml file and insert the DataTemplate in the resource dictionary like this:

    <DataTemplate x:Key="ListItemTemplate"> 
        <ViewCell> 
          <StackLayout Margin="20, 15, 20, 5"> 
            <Label x:Name="NameLabel" Text="{Binding Name}"/> 
            <Label x:Name="CategoryLabel" Text="{Binding Category}"/> 
            <Label x:Name="PriceLabel" Text="{Binding Price}"/> 
          </StackLayout> 
                </ViewCell> 
      </DataTemplate> 

Now we want to set the ItemTemplate property on our ListView in the StocklistPage. Open up the StocklistPage and add the following to the ListView declaration:

        <ListView x:Name="StockItemsListView" ItemsSource="{Binding StockItems}" ItemTemplate="{StaticResource ListItemTemplate}"/> 

If we wanted to use the inline template approach, we would do this:

<ListView x:Name="StockItemsListView" ItemsSource="{Binding StockItems"> 
            <ListView.ItemTemplate> 
                <DataTemplate> 
                  <ViewCell> 
          <StackLayout Margin="20, 15, 20, 5"> 
            <Label x:Name="NameLabel" Text="{Binding Name/> 
            <Label x:Name="CategoryLabel" Text="{Binding Category}"/> 
            <Label x:Name="PriceLabel" Text="{Binding Price}"/> 
          </StackLayout> 
                  </ViewCell> 
                </DataTemplate> 
          </ListView.ItemTemplate> 
        </ListView> 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.132.194