DataTemplateByType.axaml代码
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Height="420" Width="675" xmlns:local="using:AvaloniaUI.Demos.Book._19.StoreDatabase" x:Class="AvaloniaUI.DataTemplateByType" Title="DataTemplateByType"> <Window.Resources> <local:ImagePathToBitmapConverter x:Key="ImagePathToBitmapConverter" /> </Window.Resources> <Window.DataTemplates> <DataTemplate DataType="local:Product"> <Border BorderThickness="1" BorderBrush="SteelBlue" CornerRadius="4"> <Border.Styles> <Style Selector="ListBoxItem:pointerover Border"> <Setter Property="Background" Value="LightBlue"/> </Style> <Style Selector="ListBoxItem:selected Border"> <Setter Property="Background" Value="DarkRed"/> <Setter Property="BorderBrush" Value="DarkRed"/> </Style> </Border.Styles> <Grid Margin="3" ColumnDefinitions="auto,*" RowDefinitions="auto,auto"> <Image Grid.Row="0" Grid.RowSpan="2" Width="48" Height="48" Margin="0,0,8,0" Source="{Binding ProductImagePath, Converter={StaticResource ImagePathToBitmapConverter}}" /> <TextBlock Grid.Column="1" FontWeight="Bold" Text="{Binding ModelNumber}" /> <TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding ModelName}" /> </Grid> </Border> </DataTemplate> </Window.DataTemplates> <ListBox Name="lstProducts" HorizontalAlignment="Stretch"/> </Window>
DataTemplateByType.axaml.cs代码
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using AvaloniaUI.Demos.Book._19.StoreDatabase;
using System;
using System.Linq;
namespace AvaloniaUI;
public partial class DataTemplateByType : Window
{
private StoreDb1 db = new StoreDb1();
public DataTemplateByType()
{
InitializeComponent();
lstProducts.ItemsSource = db.GetProducts();
}
}
运行效果

浙公网安备 33010602011771号