在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