WPF TreeView 绑定(demo 转)
WPF TreeView 绑定
前台:
<TreeView x:Name="tree" ItemsSource="{Binding Nodes}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:TreeNodeInfo}" ItemsSource="{Binding Path=Nodes}">
<TextBlock Background="Aqua" Text="{Binding Name}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
后台:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
namespace TreeDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
SortedDictionary<string, TreeNodeInfo> nodeList = new SortedDictionary<string, TreeNodeInfo>();
public MainWindow()
{
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Columns.Add("ParentID");
dt.Rows.Add("1", "研发部", "0");
dt.Rows.Add("2", "技术部", "0");
dt.Rows.Add("3", "销售部", "0");
dt.Rows.Add("4", "硬件组", "1");
dt.Rows.Add("5", "软件组", "1");
dt.Rows.Add("6", "软件组一", "5");
dt.Rows.Add("7", "Test", "6");
TreeNodeInfo rootNode = new TreeNodeInfo();
rootNode.ID = "0";
nodeList.Add("0", rootNode);
foreach (DataRow row in dt.Rows)
{
string id = row["ID"].ToString();
if (!nodeList.ContainsKey(id))
{
nodeList.Add(id, new TreeNodeInfo() { ID = id, Name = row["Name"].ToString(), ParentID = row["ParentID"].ToString() });
}
}
foreach (var node in nodeList.Values)
{
TreeNodeInfo tnParent = null;
if (!string.IsNullOrEmpty(node.ParentID))
{
if (nodeList.TryGetValue(node.ParentID, out tnParent))
{
tnParent.Nodes.Add(node);
}
}
}
this.DataContext = rootNode;
}
}
public class TreeNodeInfo : INotifyPropertyChanged
{
public string ID { get; set; }
public string name = "";
public string Name
{
get { return name; }
set
{
name = value;
RaisePropertyChanged("Name");
}
}
public string ParentID { get; set; }
private ObservableCollection<TreeNodeInfo> nodes = new ObservableCollection<TreeNodeInfo>();
public ObservableCollection<TreeNodeInfo> Nodes
{
get
{
return nodes;
}
}
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
特别是红颜色的字体,看不懂有没有大神解释一下,这是师傅给的Demo自己看不懂
https://www.cnblogs.com/shuang121/archive/2012/11/29/2794278.html 找到的另一种方法