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
,然后在其下添加新的Items
?
答案 0 :(得分:3)
您只需要保留对刚刚创建的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}) ;
}
}
答案 1 :(得分:0)