WPF:如何从数据库填充TreeView [英] WPF : How to Fill TreeView from DataBase
问题描述
我的表名称是Job_Type_tab
id父亲姓名
1个NULL A
2 NULL B
3 2 C
4 1 D
5 4 E
6 4 F
7 3 G
8 1 H
我想在树视图中填写此表
树必须这样填充
A
-D
--F
--E
-H
B
-C
--G
我写这段代码,但这不好
hi ,
i have this table name is Job_Type_tab
id father Name
1 NULL A
2 NULL B
3 2 C
4 1 D
5 4 E
6 4 F
7 3 G
8 1 H
and i want fill this table in treeview
the tree must be fill like this
A
-D
--F
--E
-H
B
-C
--G
iwrite this code but this not good
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var g = from h in Context.Job_Type_tab
where h.father == null
select h;
List<Job_Type_tab> j = g.ToList<Job_Type_tab>();
for (int i = 0; i < j.Count; i++ )
{
TreeViewItem treefather = new TreeViewItem();
treefather.Header = j[i].Name;
treebig.Items.Add(treefather);
Int64 id = j[i].job_type_id;
ScanChiled(id,treefather);
}
}
public void ScanChiled(Int64 father,TreeViewItem treefather)
{
if (father == null)
return;
TreeViewItem treeChiled = new TreeViewItem();
var c = from h in DLandS.Program.Context.Job_Type_tab
where h.father == father
select h;
List<DLandS.Job_Type_tab> j = c.ToList<DLandS.Job_Type_tab>();
for (int i = 0; i < j.Count; i++)
{
TreeViewItem tree = new TreeViewItem();
treefather.Header = j[i].Name;
treeChiled.Items.Add(tree);
Int64 id = j[i].job_type_id;
ScanChiled(id ,tree);
}
treefather.Items.Add(treeChiled);
}
帮帮我.........
help me.........
推荐答案
如果您使用WPF的数据绑定功能,则更容易实现.如果正在编写此代码,则将创建一个类,该类表示您要显示的数据层次结构-这将通过XAML绑定到该类.我将编写该类以使其看起来像这样:
This is much easier to achieve if you use the databinding features of WPF. If I was writing this, I''d create a class that represented the hierarchy of data that you want to display - this would be bound to from the XAML. I would write the class to look something like this:
public class JobType
{
public JobType()
{
JobTypes = new ObservableCollection<JobType>();
}
public ObservableCollection<JobType> JobTypes { get; set; }
public string Name { get; set; }
}
接下来,我将在我的视图模型中添加对此类的引用,如下所示:
Next, I''d add a reference to this class in my view model like this:
public ObservableCollection<JobType> JobTypes { get; set; }
我们将树视图绑定到此顶级项目,并使用HierarchicalDataTemplate绑定到JobType的每个实例中的JobTypes条目.
We are going to bind the treeview to this top level item, and use a HierarchicalDataTemplate to bind to the JobTypes entry in each instance of JobType.
<TreeView ItemsSource="{Binding JobTypes}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding JobTypes}" DataType="{x:Type local:JobType}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
请确保将对XAML的引用添加到包含JobType类的名称空间中(我在DataType标记中将其称为本地).
Make sure that you add a reference to your XAML to the namespace that contains the JobType class (I''ve called it local in the DataType markup).
这篇关于WPF:如何从数据库填充TreeView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!