在C#中,使用WinForms或WPF時(shí),可以通過(guò)以下方法將數(shù)據(jù)綁定到TreeView控件:
首先,創(chuàng)建一個(gè)類作為數(shù)據(jù)源。例如,我們創(chuàng)建一個(gè)名為Employee
的類:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
接下來(lái),創(chuàng)建一個(gè)BindingList<Employee>
并將其設(shè)置為T(mén)reeView的數(shù)據(jù)源:
// 創(chuàng)建數(shù)據(jù)源
BindingList<Employee> employees = new BindingList<Employee>();
employees.Add(new Employee { Id = 1, Name = "張三", Department = "技術(shù)部" });
employees.Add(new Employee { Id = 2, Name = "李四", Department = "市場(chǎng)部" });
// 將數(shù)據(jù)源設(shè)置為T(mén)reeView的數(shù)據(jù)源
treeView.DataSource = employees;
// 設(shè)置顯示的列
treeView.Columns.Add("ID", "ID");
treeView.Columns.Add("姓名", "Name");
treeView.Columns.Add("部門(mén)", "Department");
首先,創(chuàng)建一個(gè)類作為數(shù)據(jù)源。例如,我們創(chuàng)建一個(gè)名為Employee
的類:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
接下來(lái),創(chuàng)建一個(gè)ObservableCollection<Employee>
并將其設(shè)置為T(mén)reeView的數(shù)據(jù)源:
// 創(chuàng)建數(shù)據(jù)源
ObservableCollection<Employee> employees = new ObservableCollection<Employee>();
employees.Add(new Employee { Id = 1, Name = "張三", Department = "技術(shù)部" });
employees.Add(new Employee { Id = 2, Name = "李四", Department = "市場(chǎng)部" });
// 將數(shù)據(jù)源設(shè)置為T(mén)reeView的數(shù)據(jù)源
treeView.ItemsSource = employees;
在WPF中,我們還需要為T(mén)reeView的每個(gè)列設(shè)置DisplayMemberBinding
屬性以指定如何顯示數(shù)據(jù):
// 設(shè)置顯示的列
treeView.Columns.Clear();
treeView.Columns.Add(new GridViewColumn
{
Header = "ID",
DisplayMemberBinding = new Binding("Id")
});
treeView.Columns.Add(new GridViewColumn
{
Header = "姓名",
DisplayMemberBinding = new Binding("Name")
});
treeView.Columns.Add(new GridViewColumn
{
Header = "部門(mén)",
DisplayMemberBinding = new Binding("Department")
});
這樣,數(shù)據(jù)就會(huì)被綁定到TreeView控件上。