silverlight中递归构造无限级树treeview+checkbox

两个实体,其实一个实体也能构造出来,我这里是为了增加一个 checkbox

//第一个实体

public class person
{
public int no { get; set; }
public string name { get; set; }
public ObservableCollection<person> child { get; set; }
}

//第二个实体

public class inst                                       ****
{
public int instNo { get; set; }       ****
public string instName { get; set; }    ****
public int personID { get; set; }      ***
}

//xaml界面就放了一个  treeview

<Grid x:Name="LayoutRoot" Background="White">
<sdk:TreeView x:Name="tvshow" HorizontalAlignment="Left" Height="280" Margin="10,10,0,0" VerticalAlignment="Top" Width="367"/>

</Grid>

//cs页面

ObservableCollection<person> List = null;//第一个实体的集合
ObservableCollection<inst> instList = null;//第二个实体的集合      ****
public MainPage()
{
InitializeComponent();
List = new ObservableCollection<person>();
instList = new ObservableCollection<inst>();        ****
person p1 = new person() { no=1,name="1",child=new ObservableCollection<person>()};
person p2 = new person() { no = 2, name = "2", child = new ObservableCollection<person>() };
person p3 = new person() { no = 3, name = "3", child = new ObservableCollection<person>() };
person p4 = new person() { no = 4, name = "4", child = new ObservableCollection<person>() };
person p5 = new person() { no = 5, name = "5", child = new ObservableCollection<person>() };


inst inst1 = new inst() { instNo = 1,personID=1 ,instName = "jigou1" };     ***
inst inst2 = new inst() { instNo = 2, personID = 1, instName = "jigou2" };  ***
inst inst3 = new inst() { instNo = 3, personID = 1, instName = "jigou3" };  ***
inst inst4 = new inst() { instNo = 4, personID = 1, instName = "jigou4" };  ***
inst inst5 = new inst() { instNo = 5, personID = 2, instName = "jigou5" };  ***
inst inst6 = new inst() { instNo = 6, personID = 3, instName = "jigou6" };  ***
inst inst7 = new inst() { instNo = 7, personID = 4, instName = "jigou7" };  ***
p3.child.Add(p4);
p2.child.Add(p3);
List.Add(p1);
List.Add(p2);
List.Add(p5);

instList.Add(inst1); instList.Add(inst2); instList.Add(inst3); instList.Add(inst4); instList.Add(inst5); instList.Add(inst6); instList.Add(inst7);   ***

//生成树
foreach (var item in List)
{
tvshow.Items.Add(initView(item));
}
}

//递归函数
TreeViewItem initView(person p)
{
TreeViewItem it = new TreeViewItem();
it.Header = p.name;
foreach (var item in instList)
{
if (p.no == item.personID)                       ***
{
TreeViewItem cbt = new TreeViewItem();   ***
CheckBox cb = new CheckBox();              ***
cb.Content = item.instName;                    ***
cbt.Header = cb;                                     ***
it.Items.Add(cbt);                                   ***
}
}
if (p.child.Count>0)
{
foreach (var item in p.child)
{
it.Items.Add(initView(item));
}
}
return it;
}

运行效果:

如果不想 进行 复杂的 构造, 只生成第一的  无限级树, 可以把我 后面加*号的 部分  注释掉,就可以了。

原文地址:https://www.cnblogs.com/qiancheng/p/3745536.html