using System.Collections.Generic;
namespace TreeViewTest;
public interface IItem
{
string Text { get; set; }
}
public class ParentItem : IItem
{
public string Text { get; set; } = string.Empty;
public List<IItem>? Children { get; set; }
}
public class ChildItem : IItem
{
public string Text { get; set; } = string.Empty;
}
树视图数据模板选择器.cs
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml;
using System;
namespace TreeViewTest;
public class TreeViewDataTemplateSelector : DataTemplateSelector
{
public DataTemplate? ParentItemTemplate { get; set; }
public DataTemplate? ChildItemTemplate { get; set; }
protected override DataTemplate? SelectTemplateCore(object item)
{
return item switch
{
ParentItem => ParentItemTemplate,
ChildItem => ChildItemTemplate,
_ => throw new NotSupportedException(),
};
}
}
主页.xaml.cs
using Microsoft.UI.Xaml.Controls;
using System.Collections.Generic;
namespace TreeViewTest;
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
Items.Add(new ParentItem()
{
Text = "Test tree1",
Children = new List<IItem>()
{
new ChildItem() {Text = "Test tree1 child" },
new ChildItem() {Text = "Test tree1 child2" },
}
});
Items.Add(new ParentItem()
{
Text = "Test tree2",
Children = new List<IItem>()
{
new ChildItem() {Text = "Test tree2 child" },
new ChildItem() {Text = "Test tree2 child2" },
}
});
Items.Add(new ParentItem()
{
Text = "Test tree3",
Children = new List<IItem>()
{
new ChildItem() {Text = "Test tree3 child" },
new ChildItem() {Text = "Test tree3 child2" },
}
});
}
public List<IItem> Items { get; set; } = new();
}
1条答案
按热度按时间p5cysglq1#
一种方法是“隐藏”
CheckBox
。您可以使用DataTemplateSelector
定位项目。检查以下示例代码:项目.cs
树视图数据模板选择器.cs
主页.xaml.cs
主页.xaml