溫馨提示×

如何在C#中實(shí)現(xiàn)TreeListView的節(jié)點(diǎn)添加和刪除

c#
小樊
152
2024-08-13 10:30:39
欄目: 編程語言

在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,用來存儲樹節(jié)點(diǎn)數(shù)據(jù)。在MainViewModel中還實(shí)現(xiàn)了AddNode和RemoveNode方法,用來添加和刪除節(jié)點(diǎn)。最后在XAML中使用TreeView和HierarchicalDataTemplate來顯示樹節(jié)點(diǎn)數(shù)據(jù)。當(dāng)調(diào)用AddNode和RemoveNode方法時(shí),樹節(jié)點(diǎn)的顯示會相應(yīng)地更新。

0