如何从DataBase填充TreeView

时间:2011-10-22 07:02:12

标签: wpf

我有一个表(Hesab)whit 3字段(ID,Name,FatherID),并使用EF。

ID fatherID名称

1 NULL A

2 NULL B

3 2 C

4 1 D

5 4 E

6 4 F

7 3 G

8 1 H

我希望在treeview中填写此表

树必须像这样填充 一个 -D - F --e -H 乙 -C --g

我创建了这个类

   class Hesabs:Hesab
    {
    public Hesabs()
    {
        AllHesab = new ObservableCollection<Hesab>();
    }
    public ObservableCollection<Hesab> AllHesab { get; set; }
           }

和ViewModel

     public ObservableCollection<Hesabs> AllHesab { get; set; }
    public ObservableCollection<Hesabs> FirstHesab { get; set; }

    public ViewModelHesabs()
    { 
        CRMEntities crm=new CRMEntities();

        var ls = from h in crm.Hesab
                 where (h.FatherID == null)
                 select h;
        ObservableCollection<Hesabs> hes = new ObservableCollection<Hesabs>();
        foreach (Hesab hh in ls.ToList())
        {
            var ls2 = from h in crm.Hesab
                      where (h.FatherID == hh.ID)
                      select h;
            Hesabs hesab = new Hesabs();
            hesab.Name = hh.Name;
            hesab.ID = hh.ID;
            hesab.AllHesab = new ObservableCollection<Hesab>(ls2.ToList());
            hes.Add(hesab);
        }
        FirstHesab = hes;
    }

和xaml

        <TreeView ItemsSource="{Binding FirstHesab}">
        <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding AllHesab}" DataType="         {x:Type local:Hesabs}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}"  Tag="{Binding ID}"/>
                </StackPanel>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>

但填写2级:(

1 个答案:

答案 0 :(得分:1)

您只检查FatherId == null的元素并分配他们的孩子 - 这就是为什么您只在树中获得一个级别的层次结构。变化:

foreach (Hesab hh in ls.ToList())

为:

foreach (Hesab hh in crm.Hesab.ToList())
{
    // ...
    // also assign father id, you'll need it to extract actual root elements
    hesab.FatherId = hh.FatherId;
}

要获取根元素,只需查询hes.Where(h => h.FatherId == null)并将其分配给FirstHesab

另一方面,您的视图模型可能更好,而不是您可以拥有的Hesabs课程:

class HesabViewModel
{
    HesabViewModel(Hesab hesab)
    {
        // set properties you'd like to expose to View, eg:
        this.Name = hesab.Name;
        this.Children = new ObservableCollection<HesabViewModel>();
    }

    public string Name { get; set; }
    public ObservableCollection<HesabViewModel> Children { get; private set; }
}

基本上,您的视图模型类应该可以更轻松地访问视图的模型对象。继承(就像你现在一样),可能不是最好的方法 - 它并不真正将模型与视图分开。