BoundTreeView.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="300" Width="300"
        xmlns:local="using:AvaloniaUI"
        xmlns:data="using:AvaloniaUI.Demos.Book._19.StoreDatabase"
        x:Class="AvaloniaUI.BoundTreeView"
        Title="BoundTreeView">

    <TreeView Name="treeCategories" x:DataType="local:BoundTreeView"
              Margin="5"
              ItemsSource="{Binding Categories}">
        
        <TreeView.DataTemplates>

            <TreeDataTemplate x:DataType="data:Category"
                              ItemsSource="{Binding Products}">
                <TextBlock Text="{Binding CategoryName}" />
            </TreeDataTemplate>

            <TreeDataTemplate x:DataType="data:Product">
                <TextBlock Text="{Binding ModelName}" />
            </TreeDataTemplate>

        </TreeView.DataTemplates>
    </TreeView>
</Window>

BoundTreeView.axaml.cs代码

using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using AvaloniaUI.Demos.Book._19.StoreDatabase;
using System.Collections.ObjectModel;

namespace AvaloniaUI;

public partial class BoundTreeView : Window
{
    private StoreDb1 db = new StoreDb1();
    public ObservableCollection<Category> Categories { get; }
    public BoundTreeView()
    {
        InitializeComponent();
        Categories = db.GetCategoriesAndProducts();
        this.DataContext = this;
    }
}

运行效果

image

 

posted on 2026-02-16 10:04  dalgleish  阅读(8)  评论(0)    收藏  举报