首页 WinForm/WPF materialdesign之Tree动态加载

materialdesign之Tree动态加载

作者:胡同里的砖头 围观群众:247 更新于:2023-08-18

先在窗体中添加命名空间的引用xmlns:models="clr-namespace:WpfApp5.Models"


<TreeView  x:Name="treeView"  ItemsSource="{Binding NavMenus}" Width="200px" >
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type models:NavMenuModel}" ItemsSource="{Binding ChildMenus}">
<TextBlock Text="{Binding MenuName}" Margin="3 2" />
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type models:MenuModel}">
<TextBlock Text="{Binding MenuName}" Margin="3 2" />
</DataTemplate>
</TreeView.Resources>
</TreeView>
Model代码:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp5.Models
{
public class NavMenuModel : MenuModel
{
public NavMenuModel()
{
ChildMenus = new ObservableCollection<MenuModel>();
}
public ObservableCollection<MenuModel> ChildMenus { get; }
}
public class MenuModel
{
public int Id { get; set; }

public int ParentId { get; set; }

public string MenuName { get; set; }
public MenuModel()
{
}
public MenuModel(int menuId, string menuName, int parentMenuId, params MenuModel[] subItems)
{
this.Id = menuId;
this.MenuName = menuName;
this.ParentId = parentMenuId;
}
}
}


窗体后台动态加载菜单代码:
public MainWindowModel() {
LeftMenuViewModel();
}

[ObservableProperty]
public ObservableCollection<NavMenuModel> navMenus;

public void LeftMenuViewModel()
{
NavMenus = new ObservableCollection<NavMenuModel>();
var menu = new NavMenuModel() { Id = 1, MenuName = "Chapter 1" };

var subMenu = new NavMenuModel() { Id = 11, MenuName = "Chapter 1.1", ParentId = 1 };
subMenu.ChildMenus.Add(new MenuModel() { Id = 111, MenuName = "Chapter 1.1.1", ParentId = 11 });
menu.ChildMenus.Add(subMenu);

NavMenus.Add(menu);
var m2 = new NavMenuModel() { Id = 2, MenuName = "Chapter 2" };

var subMenu2 = new NavMenuModel() { Id = 21, MenuName = "Chapter 2.1", ParentId = 1 };

m2.ChildMenus.Add(subMenu2);
NavMenus.Add(m2);
NavMenus.Add(new NavMenuModel() { Id = 3, MenuName = "Chapter 3" });


}
效果如图:

  • 本文标题: materialdesign之Tree动态加载
  • 文章分类:【WinForm/WPF】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8