UWP How to define DataTemplate in App.XAML

I want to define a Datatemplate in App.XAML and then share it for any page, I need to use this itemtemplate template. I do not know how to do that.

+4
source share
1 answer

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

If you use the standard XAML binding , everything will be the same as in WPF:

  • 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>
    
  • Link to the template on the page:

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

If you use a compiled {x:bind}binding , you will need to define the templates in a separate resource dictionary with code, behind which will be the generated code:

  • :

    public partial class DataTemplates
    {
        public DataTemplates()
        {
            InitializeComponent();
        }
    }
    
  • :

    <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>
    
  • Application.Resources:

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <local:DataTemplates/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
    
  • , :

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

. , .

+10

All Articles