在上一篇文章,已介绍了如何绑定数据到TreeListControl控件的List部分。如果没有实现TreeListControl控件的Tree功能,这个控件就没有意义了。实现Tree功能,关键是处理好各个节点的父子关系,下面就介绍如何在TreeListControl控件的Tree部分设置各个节点的父子关系。
TreeListControl控件的TreeListView元素有两个属性,分别是KeyFieldName和ParentFieldName,KeyFieldName是主键,即当前节点,ParentFieldName是当前节点的父节点。处理好这两个属性,就实现了各个节点的父子关系。
首先,在XAML如下声明:
<my:TreeListControl Grid.Row="1" Name="treeList" >
<my:TreeListControl.Columns>
<my:TreeListColumn FieldName="strName" Header="Register Name" />
<my:TreeListColumn FieldName="strNum" Header="Register Num" />
</my:TreeListControl.Columns>
<my:TreeListControl.View>
<my:TreeListView Name="treeListView" KeyFieldName="strKeyName" ParentFieldName="strParentName">
</my:TreeListView>
</my:TreeListControl.View>
</my:TreeListControl>
其次,在声明类添加如下:
public class tempClass
{
public string strName { get; set; }
public string strNum { get; set; }
public string strKeyName { get; set; }
public string strParentName { get; set; }
}
最后,函数实现:
public partial class EditUiPage : Page
{
private readonly ObservableCollection<tempClass> _list = new ObservableCollection<tempClass>();
public EditUiPage()
{
InitializeComponent();
InitTreeList();
}
private void InitTreeList()
{
List<tempClass> strList = new List<tempClass>();
string str;
for (int i = 0; i < 10; i++)
{
tempClass tc = new tempClass();
str = "No." + (i + 1).ToString();
tc.strName = "NAAAAA";
tc.strNum = str;
if (i < 5)
{
tc.strKeyName = "Key" + (i + 1).ToString();
tc.strParentName = "Key" + (i + 1).ToString();
}
else
{
tc.strKeyName = "Key" + (i + 1).ToString();
tc.strParentName = "Key" + (i + 1-5).ToString();
}
strList.Add(tc);
_list.Add(tc);
}
this.treeList.ItemsSource = strList;
//this.treeList.ItemsSource = _list;
}
}
我在研究
TreeListControl控件,有个疑问:决定父子节点的KeyFieldName和ParentFieldName属性,与TreeListColumn的各个FieldName怎么关联起来?
在我的第一感觉,KeyFieldName和ParentFieldName属性要关联某一列,这样才能让Tree与List联动起来。经过一阵揣摩,才明白,KeyFieldName才是串联Tree和List的关键因素,包括以下几点:
1)每一行数据,包括TreeListColumn的各个FieldName对应的数据,也包括KeyFieldName和ParentFieldName属性对应的数据。KeyFieldName和ParentFieldName不在控件上显示,起关联各行数据的作用。
2)在同一笔数据(即多行数据),KeyFieldName是唯一的,不能重复。
3)当某一行的KeyFieldName成为其他行的ParentFieldName时,此行就是其他行的父节点。当某行的ParentFieldName不是其他行的KeyFieldName,此为根节点。
4)KeyFieldName和ParentFieldName属性可以和TreeListColumn的各个FieldName无关,可以任意赋值,只要满足第2)和第3)即可。但一般情况下,某一列的值具有不重复性,且具有父子的关联,则可以拿来赋值给KeyFieldName和ParentFieldName属性。
上述代码的运行效果如下: