none
EntityFramework的數據怎麼綁定到WPF的TreeView控件裡 RRS feed

  • 问题

  • Entity Framework的code:

     public class sort
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public virtual ICollection<sort> sorts { get; set; }
        }
     public class myDb : DbContext
        {
            public DbSet<sort> sorts { get; set; }
        }

    然後裡面加了幾個分類都能正常的存取。嵌套。

    using (var context = new myDb())
                {
                    var r1 = new sort {Name = "Lei1"};
                    var r3 = new sort {Name = "Lei3"};
                    var r5 = new sort {Name = "Lei5"};
                    var r4 = new sort {Name = "Lei4"};
                    r4.sorts = new Collection<sort>() {r1};
                    r1.sorts = new Collection<sort>() {r3};
                    r5.sorts = new Collection<sort>() {r4};
                    context.Entry(r5).State = EntityState.Added;
                    context.SaveChanges();
                }
    ID    Name    sort_ID
    1    Lei5    NULL
    2    Lei4    1
    3    Lei1    2
    4    Lei3    3
     <Window.Resources>
            <ResourceDictionary>
                <HierarchicalDataTemplate   x:Key="CheckBoxItemTemplate" DataType="{x:Type dal:sort}" ItemsSource="{Binding sorts}">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Name}"/>
                    </StackPanel>
                </HierarchicalDataTemplate>
            </ResourceDictionary>
        </Window.Resources>
        <Grid>
            <TreeView Name="TreeView1"   ItemsSource="{Binding}" ItemTemplate="{StaticResource CheckBoxItemTemplate}">
            </TreeView>
        </Grid>
     var r6 = context.sorts.FirstOrDefault(x => x.Name == "Lei5");
                    TreeView1.ItemsSource = new Collection<sort>() { r6 };

    網上很多例子.但是EntityFramework的數據這樣不行.只顯示一個節點.不知道是怎麼回事.

    求指點.




    2013年3月29日 11:19

全部回复