wpf 自定义treeview 如何获得树节点集合 10

 我来答
Mickal小米
2012-04-09 · TA获得超过3666个赞
知道大有可为答主
回答量:1542
采纳率:100%
帮助的人:1756万
展开全部
给段我改写的代码,编译通过的。
数据类:
public class LeafNode
{
private string data;

public string Data
{
get { return data; }
set { data = value; }
}

private List<LeafNode> children;

public List<LeafNode> Children
{
get { return children; }
set { children = value; }
}
}
前台代码:
<Window.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:LeafNode}" ItemsSource="{Binding Path=Children}">
<TextBlock Text="{Binding Path=Data}" ToolTip="{Binding Path=Data}"/>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid>
<TreeView x:Name="twLeaf"/>
<Button Name="btn" Click="btn_Click" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="5" Width="50" Height="25" Content="click"/>
</Grid>
后台代码:
List<LeafNode> roots = new List<LeafNode>();
List<LeafNode> roots1 = new List<LeafNode>();

public test3()
{
InitializeComponent();

for (int i = 0; i < 5; i++)
{
LeafNode child = new LeafNode() { Data = "root" + i.ToString() };
child.Children = new List<LeafNode>();
roots.Add(child);

for (int j = 0; j < 10; j++)
{
LeafNode subchild = new LeafNode() { Data = "son" + j.ToString() };
subchild.Children = new List<LeafNode>();
child.Children.Add(subchild);

for (int k = 0; k < 15; k++)
{
LeafNode gs = new LeafNode() { Data = "grantSon" + k.ToString() };
subchild.Children.Add(gs);
}
}
}
twLeaf.ItemsSource = roots;
}
private void btn_Click(object sender, RoutedEventArgs e)
{
roots1.Clear();

for (int i = 0; i < twLeaf.Items.Count; i++)
{
LeafNode rootItem = twLeaf.Items[i] as LeafNode;
if (rootItem != null)
{
GetTreeviewNodes(null,rootItem);
}
}
}

private void GetTreeviewNodes(LeafNode parentNode, LeafNode twItem)
{
LeafNode node = new LeafNode()
{
Data = twItem.Data,
Children = new List<LeafNode>()
};
if (parentNode != null)
{
parentNode.Children.Add(node);
}
else
{
roots1.Add(node);
}
if (twItem.Children!=null && twItem.Children.Count > 0)
{
for (int i = 0; i < twItem.Children.Count; i++)
{
LeafNode item = twItem.Children[i] as LeafNode;
if (null != item)
{
GetTreeviewNodes(node, item);
}
}
}
else
{
return;
}
}
说明:roots是给treeview赋值的,roots1是通过按钮事件获取treeview节点集合的。
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式