在C#中,可以使用WPF的TreeView和ListView結(jié)合的方式來實(shí)現(xiàn)TreeListView。以下是一個(gè)簡單的示例代碼,展示如何實(shí)現(xiàn)TreeListView的節(jié)點(diǎn)添加和刪除:
// 創(chuàng)建一個(gè)實(shí)體類,表示樹節(jié)點(diǎn)的數(shù)據(jù)
public class TreeNode
{
public string Name { get; set; }
public ObservableCollection<TreeNode> Children { get; set; }
public TreeNode()
{
Children = new ObservableCollection<TreeNode>();
}
}
// 在ViewModel中創(chuàng)建樹節(jié)點(diǎn)數(shù)據(jù)
public class MainViewModel
{
public ObservableCollection<TreeNode> Nodes { get; set; }
public MainViewModel()
{
Nodes = new ObservableCollection<TreeNode>
{
new TreeNode { Name = "Node 1", Children = new ObservableCollection<TreeNode>
{
new TreeNode { Name = "Child Node 1" },
new TreeNode { Name = "Child Node 2" }
}},
new TreeNode { Name = "Node 2" }
};
}
// 添加節(jié)點(diǎn)操作
public void AddNode(TreeNode parent, string nodeName)
{
parent.Children.Add(new TreeNode { Name = nodeName });
}
// 刪除節(jié)點(diǎn)操作
public void RemoveNode(TreeNode node)
{
if (node != null)
{
node.Parent.Children.Remove(node);
}
}
}
// XAML代碼
<TreeView ItemsSource="{Binding Nodes}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
在上面的示例中,我們首先創(chuàng)建了一個(gè)TreeNode實(shí)體類,表示樹節(jié)點(diǎn)的數(shù)據(jù)。然后在MainViewModel中創(chuàng)建了一個(gè)ObservableCollection