Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UWP How to define DataTemplate in App.XAML

I Want to define Datatemplate in App.XAML and then shared it for any page i need to use this itemtemplate. I don't know how to do it

like image 418
Huy Lê Quang Avatar asked Mar 05 '16 07:03

Huy Lê Quang


1 Answers

It depends on the type of binding, you want to use.

If you're using standard XAML binding, everything is the same as in WPF:

  1. Define the template in Application.Resources:

    <Application.Resources>
        <DataTemplate x:Key="Template1">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Prop1}" />
                <TextBox Text="{Binding Prop2}" />
            </StackPanel>
        </DataTemplate>
    </Application.Resources>
    
  2. Reference the template in the page:

    <ListView ItemsSource="{Binding Items}" ItemTemplate="{StaticResource Template1}" />
    

If you're using compiled {x:bind} binding, you'll need to define the templates in a separate resource dictionary with code behind where the generated code will end up:

  1. Create a new partial class for the resource dictionary:

    public partial class DataTemplates
    {
        public DataTemplates()
        {
            InitializeComponent();
        }
    }
    
  2. Create a resource dictionary based on this partial class with the data template:

    <ResourceDictionary
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:MyNamespace"
        x:Class="MyNamespace.DataTemplates">
    
        <DataTemplate x:Key="Template2" x:DataType="local:MyClass">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{x:Bind Prop1}" />
                <TextBox Text="{x:Bind Prop2}" />
            </StackPanel>
        </DataTemplate>
    </ResourceDictionary>
    
  3. Merge the resource dictionary into Application.Resources:

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <local:DataTemplates/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
    
  4. Finally use the template in the page:

    <ListView ItemsSource="{Binding Items}" ItemTemplate="{StaticResource Template2}" />
    

You can check Igor's blog post for more details. Nothing significant has changed since the preview when the post was published.

like image 78
Damir Arh Avatar answered Sep 16 '22 15:09

Damir Arh