本文主要是介绍Avalonia TreeView 示例代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
参考文档
https://docs.avaloniaui.net/docs/reference/controls/detailed-reference/treeview-1
新建一个avalonia MVVM工程AvaloniaAppTreeview,删掉MainWindow.xaml里的<TextBlock Text="{Binding Greeting}" HorizontalAlignment="Center" VerticalAlignment="Center"/> ,
添加以下定义
<TreeView ItemsSource="{Binding Nodes}">
<TreeView.ItemTemplate>
<TreeDataTemplate ItemsSource="{Binding SubNodes}">
<TextBlock Text="{Binding Title}"/>
</TreeDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
在Models目录下,新建Node.cs, 复制如下内容到Node.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AvaloniaAppTreeview.Models
{
public class Node
{
public ObservableCollection<Node>? SubNodes { get; set; }
public string Title { get; set; }
public Node(string title)
{
Title = title;
}
public Node(string title, ObservableCollection<Node> subNodes)
{
Title = title;
SubNodes = subNodes;
}
}
}
MainWindowViewModel.cs的内容如下:
using AvaloniaAppTreeview.Models;
using System.Collections.ObjectModel;
namespace AvaloniaAppTreeview.ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
#pragma warning disable CA1822 // Mark members as static
//public string Greeting => "Welcome to Avalonia!";
public ObservableCollection<Node> Nodes { get; }
public MainWindowViewModel()
{
Nodes = new ObservableCollection<Node>
{
new Node("Animals", new ObservableCollection<Node>
{
new Node("Mammals", new ObservableCollection<Node>
{
new Node("Lion"), new Node("Cat"), new Node("Zebra")
})
})
};
}
#pragma warning restore CA1822 // Mark members as static
}
}
这篇关于Avalonia TreeView 示例代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!