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
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:
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>
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:
Create a new partial class for the resource dictionary:
public partial class DataTemplates
{
public DataTemplates()
{
InitializeComponent();
}
}
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>
Merge the resource dictionary into Application.Resources
:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<local:DataTemplates/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With