DataTemplates
As styles aren't stored in Resources, neither are DataTemplates. Instead, DataTemplates are placed in a DataTemplates collection on each control (and on Application):
1
<UserControl xmlns:viewmodels="clr-namespace:MyApp.ViewModels;assembly=MyApp">
2
<UserControl.DataTemplates>
3
<DataTemplate DataType="viewmodels:FooViewModel">
4
<Border Background="Red" CornerRadius="8">
5
<TextBox Text="{Binding Name}"/>
6
</Border>
7
</DataTemplate>
8
</UserControl.DataTemplates>
9
<!-- Assuming that DataContext.Foo is an object of type
10
MyApp.ViewModels.FooViewModel then a red border with a corner
11
radius of 8 containing a TextBox will be displayed here -->
12
<ContentControl Content="{Binding Foo}"/>
13
<UserControl>
Copied!
Data templates in Avalonia can also target interfaces and derived classes (which cannot be done in WPF) and so the order of DataTemplates can be important: DataTemplates within the same collection are evaluated in declaration order so you need to place them from most-specific to least-specific as you would in code.
Last modified 5mo ago
Export as PDF
Copy link