其他分享
首页 > 其他分享> > CodeGo.net>如何将一个TreeViewItem到生成的TreeViewItem?

CodeGo.net>如何将一个TreeViewItem到生成的TreeViewItem?

作者:互联网

C#:

TreeViewItem treeItem = null;
        treeItem = new TreeViewItem();
        treeItem.Header = "Audit";


        foreach (cAuditTransactionTypeEntity tt in _Pot)
        {
            char[] charsToTrim = {' ', '\t' };
            treeItem.Items.Add(new TreeViewItem() { Header = tt.TransactionType, Name = tt.TransactionType.Replace(" ", "")});
        }

        ToDoList.Items.Add(treeItem);

XAML:

<TreeView x:Name="MyTreeView" HorizontalAlignment="Left" Height="430" Margin="381,409,0,0" VerticalAlignment="Top" Width="616">
        <TreeViewItem Name="ToDoList" Header="To Do List" FontSize="20" IsExpanded="True">  
        </TreeViewItem>
    </TreeView>

我已经将TreeViewItems添加到TreeView中,如上所示.现在,我需要在每个生成的TreeViewItems下添加更多项目.但是,如XAML所示(也如上所示),尚未添加新生成的项目,因此我无法命名它们以在代码中引用它们.

treeItem.Items.Add(new TreeViewItem() { Header = tt.TransactionType, Name = tt.TransactionType.Replace(" ", "")});

因此,我在代码的这一部分中添加了名称生成.此外,此尝试失败,并且仍无法引用我生成的TreeViewItems,因为名称仅在运行时生成.

是否有另一种解决方法,还是有另一种方法可以在代码中找到这些生成的TreeViewItems中的每一个,然后在它们下面添加新的Item?

解决方法:

您只需要保留对刚刚创建的TreeViewItem的引用,然后将项目添加到该treeViewItem

TreeViewItem treeItem = null;
treeItem = new TreeViewItem();
treeItem.Header = "Audit";


foreach (cAuditTransactionTypeEntity tt in _Pot)
{
    TreeViewItem createdTV ;

    char[] charsToTrim = {' ', '\t' };

    //Keep a reference to the created TreeViewItem
    createdTV = new TreeViewItem() { Header = tt.TransactionType, Name = tt.TransactionType.Replace(" ", "")}

    //Create the childs of the createdTreeView

    foreach (cAuditTransactionTypeEntity otherInfo in _OtherList)
    {
        createdTV.Items.Add(new TreeViewItem() { Header = otherInfo.TransactionType, Name = otherInfo.TransactionType.Replace(" ", "")}) ;
    }

    treeItem.Items.Add(createdTV);
}

ToDoList.Items.Add(treeItem);

如果您需要做的是寻找一个特定的孩子并向其中添加项目…

foreach (TreeviewItem objTreeviewItem in ToDoList.Items) 
{
    //change to the desired transaction type
    if ((objTreeviewItem.Header == "TransType")) in your comments
    {
        //add the IDs that correspond to the transaction type
        objTreeviewItem.Items.Add(new TreeViewItem() { Header = child.ID, Name = child.Name}) ;
    }

}

标签:treeview,treeviewitem,wpf,xaml,c
来源: https://codeday.me/bug/20191122/2059083.html