地基系列九 wpf_MVVM_009 创建树形节点

创建树形节点:
(1):声明树形节点类,用于存储节点图标、名称、类型、ID、子集合。
(2):在XAML中构建好TreeView资源,用于显示节点数据。
(3):在逻辑代码中自定义树形节点数据,赋值给类;
(4):给TreeView的ItemSource赋值。
例子:
(1)
//在文件夹“_10Base”,声明TreeView类,存储图标、名字、叶节点集合
public class TV()
{
public string TvIcon { get ; set ; }
public string TvName { get ; set ; }
public List TvList { get ; set ; }
}
(2)
注意:【1】在命名空间中加上对类“TV()”的引用, 我把它命名为 " myTree " , 例子,
<UserControl x:Class=“客户端._07Basice.UserControl3”

xmlns:myTree=“clr-namespace:客户端._10Base”

<TreeView Name="myTreeView">
	<TreeView.Resources>
		<HierarchicalDataTemplate DataType="{x:Type myTree:TV }" 
				           ItemsSource = "{ Binding TvList , Mode = TwoWay , UpdateSourceTrigger=PropertyChanged }">
			<StackPanel Orientation="Horizontal" Margin="0,2" >
				<Image Height="18" Source="{ Binding TvIcon,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged }">
				</Image>
				<TextBlock Text="{Binding TvName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged }">
				</TextBlock>
			</StackPanel>
		</HierarchicalDataTemplate>
	</TreeView.Resources>
</TreeView >

注意【1】:新建的类,常常会出现“找不到…”“不存在…” ,需要在确认代码正确和类的路径没有错误,然后, “重新生成解决方案”,或者重新启动"VS"。

(3):
[1]: 先引用命名空间
	using 客户端._10Base;
[2]:声明叶节点集合
private static List<TV> TVList1;
private static List<TV> TVList2;
private static List<TV> SelectTreeView()
{
	TVList = new List<TV>();
	for( int i = 0; i < 5 ; i ++ )
	{
		TVList2 = new List<TV>();
		for( int r = 0 ; r < 2 ; r ++ )
		{
			TV tvList2 = new TV();
			tvList2.TvIcon = "/../../Image/Afoot2.png"
			tvList2.TvName = "第二层子节点中的第"+r+"个节点";
			tvList2.TvList = new List<TV>();
			TVList2.Add(tvList2);
		}
		  TV tvList1 = new TV();
           			   tvList1.TvIcon = "/../../Images/Afoot3.png";
          			   tvList1.TvName = "第一层子节点"+i+"";
          			   tvList1.TvList = TVList2;
              		  TVList1.Add(tvList1);
	}
	 List<TV> TV0 = new List<_10Base.TV>()
           		 {
          		      new TV(){
                		    TvIcon = "/../../Images/Afoot1.png",
             		    TvName = "顶层父节点",
                		    TvList = TVList1,
            		    }
         		   };
      	      return TV0;
}
(4)
private void Main()
{
	List<TV> stvTask = SelectTreeView();
	this.myTreeView.ItemsSource = stvTask ;
}

注意:【1】:在(界面)XAML中声明命名空间 的组成: “项目名称+文件夹名字”;
与在(逻辑)代码中声明命名空间 的组成: “项目名称+问价夹名字”;
它们两个是一样的组成,如果实际存在的类,在命名空间中显示“不存在…”,就点击项目,选择“重新生成解决方案”。
【2】:对于树形节点的类的字段,可以定义无限个,例子,
public class TV
{
//同时也可以使用构造函数去初始化
public TV()
{
this.TvIcon = “/…/…/需要的默认图标”;
this.TvName =“默认名字”;
}
public string TvIcon { get; set; }
public string TvName { get; set; }
public List TvList { get; set; }
public TvType TvType { get; set; }
public string TvID { get; set; }
}
public enum TvType
{
TvFather,//根
TvSon,//叶
TvStruct//结构
}
【3】在(界面)中调用类中的成员,使用Binding 关键字:

如果调用的字段,在类中找不到,则不显示内容。而不会报错。

发布了131 篇原创文章 · 获赞 36 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44548307/article/details/104800219