在C#中,可以使用WPF的TreeView和ListView结合的方式来实现TreeListView。以下是一个简单的示例代码,展示如何实现TreeListView的节点添加和删除:
// 创建一个实体类,表示树节点的数据
public class TreeNode
{
public string Name { get; set; }
public ObservableCollection<TreeNode> Children { get; set; }
public TreeNode()
{
Children = new ObservableCollection<TreeNode>();
}
}
// 在ViewModel中创建树节点数据
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" }
};
}
// 添加节点操作
public void AddNode(TreeNode parent, string nodeName)
{
parent.Children.Add(new TreeNode { Name = nodeName });
}
// 删除节点操作
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>
在上面的示例中,我们首先创建了一个TreeNode实体类,表示树节点的数据。然后在MainViewModel中创建了一个ObservableCollection