先在窗体中添加命名空间的引用xmlns:models="clr-namespace:WpfApp5.Models"
<TreeView x:Name="treeView" ItemsSource="{Binding NavMenus}" Width="200px" >Model代码:
<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>
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】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.