ExpandingDataTemplate.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="424" Width="355" xmlns:local="using:AvaloniaUI.Demos.Book._19.StoreDatabase" x:Class="AvaloniaUI.ExpandingDataTemplate" Title="ExpandingDataTemplate"> <Window.Resources> <local:ImagePathToBitmapConverter x:Key="ImagePathConverter"/> <DataTemplate x:Key="ProductTemplate" x:DataType="local:Product"> <Grid Background="White"> <!-- Border 背景绑定到 ListBoxItem.Background,这样选中时改变 ListBoxItem 背景,Border 会跟着变 --> <Border Margin="5" BorderThickness="1" BorderBrush="SteelBlue" CornerRadius="4" Background="{Binding $parent[ListBoxItem].Background}"> <StackPanel Margin="3"> <!-- 始终显示的部分 --> <TextBlock Text="{Binding ModelName}" /> <!-- 只在选中时显示的部分:用 IsVisible 绑定父 ListBoxItem.IsSelected --> <StackPanel Margin="3" IsVisible="{Binding $parent[ListBoxItem].IsSelected}"> <TextBlock Margin="3" Text="{Binding Description}" TextWrapping="Wrap" MaxWidth="250" HorizontalAlignment="Left" /> <Image Source="{Binding ProductImagePath, Converter={StaticResource ImagePathConverter}}" /> <Button FontWeight="Normal" HorizontalAlignment="Right" Padding="1" Click="OnViewDetailsClick" Tag="{Binding .}"> View Details... </Button> </StackPanel> </StackPanel> </Border> </Grid> </DataTemplate> </Window.Resources> <ListBox x:Name="lstCategories" Grid.Row="1" Margin="10" HorizontalAlignment="Stretch" ItemTemplate="{StaticResource ProductTemplate}"> <ListBox.Styles> <!-- 取消默认 Padding --> <Style Selector="ListBoxItem"> <Setter Property="Padding" Value="0" /> </Style> <!-- 选中时改变字体和背景 --> <Style Selector="ListBoxItem:selected"> <Setter Property="FontWeight" Value="Bold" /> <Setter Property="Background" Value="LightSteelBlue" /> </Style> </ListBox.Styles> </ListBox> </Window>
ExpandingDataTemplate.axaml.cs代码
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using AvaloniaUI.Demos.Book._19.StoreDatabase;
namespace AvaloniaUI;
public partial class ExpandingDataTemplate : Window
{
private StoreDb1 db = new StoreDb1();
public ExpandingDataTemplate()
{
InitializeComponent();
lstCategories.ItemsSource = db.GetProducts();
}
private void OnViewDetailsClick(object? sender, RoutedEventArgs e)
{
}
}
运行效果

浙公网安备 33010602011771号