Skip to main content
Version: 11.0.x

Reusing Data Templates

If you define a data template in the Window.DataTemplates collection (as on the previous page), you can reuse it anywhere in the window. However, you can also extend the reuse of a data template to any window in your application.

This works because Avalonia UI performs a hierarchical search of its logical tree to choose a data template. At its most extensive, the search starts in a control, extends to any parent controls (recursively), then looks in the window (as on the previous page), and finally looks at the application itself for a data templates collection.


From more information on the logical tree concept in Avalonia UI , see here.

Therefore if you want to reuse a template in any window of your application: define templates in the Application.DataTemplates collection, located in the app.axaml file.

To see how this works, first add another view model as follows:

namespace MySample
public class Teacher
public string Name { get; set; } = String.Empty;
public string Subject { get; set; } = String.Empty;

And in the app.axaml file, add a data template for the type Teacher:

<Application xmlns=""
<FluentTheme />

<DataTemplate DataType="{x:Type vm:Teacher}">
<Grid ColumnDefinitions="Auto,Auto" RowDefinitions="Auto,Auto">
<TextBlock Grid.Row="0" Grid.Column="0">Name:</TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Name}"/>
<TextBlock Grid.Row="1" Grid.Column="0">Subject:</TextBlock>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Subject}"/>

Use a local definition of a teacher in the window content zone:

<Window xmlns=""
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
<DataTemplate DataType="{x:Type local:Student}">
<Grid ColumnDefinitions="Auto,Auto" RowDefinitions="Auto,Auto">
<TextBlock Grid.Row="0" Grid.Column="0">First Name:</TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding FirstName}"/>
<TextBlock Grid.Row="1" Grid.Column="0">Last Name:</TextBlock>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding LastName}"/>

<local:Teacher Name="Dr Jones" Subject="Maths"/>

Although there is no data template for a teacher in the window; Avalonia UI will find the template you defined in the application, and the display works as planned:


Remember to specify a DataType in every data template, wherever it is defined, because if Avalonia UI fails to find a data template match for your data; then nothing will be displayed!