2015-10-20 5 views
0

У меня возникли проблемы с заполнением дочерних узлов TreeView в моем приложении. Я не знаю, почему мой объект: objProd не хочет, чтобы загрузить свои объекты из линии objProd.ConsultationTypes.Load(); нагрузки() функция дает мне эту ошибку:Заполнение дочерних узлов управления TreeView

Error 2 'System.Collections.Generic.ICollection<_ConfigurationPortal.ConsultationType>' does not contain a definition for 'Load' and no extension method 'Load' accepting a first argument of type 'System.Collections.Generic.ICollection<_360ClientConfigurationPortal.ConsultationType>' could be found (are you missing a using directive or an assembly reference?) C:\Programming\Source\Workspaces\360ClientConfigurationPortal\360ClientConfigurationPortal\MainPage.xaml.cs 151 51 360ClientConfigurationPortal

Вот мой код блока от того, где объект оклики. Этот кодовый блок является инициированным событием, которое реагирует, когда вы нажимаете на узел, чтобы его развернуть.

private void ExpandLevel(TreeViewItem parentItem) 
      { 
       if (parentItem.Header.Equals("Features"));      // == typeof(Product)) //Check that the parent items are of type product as we want to fill their inner nodes. 
       { 
        Product objProd = parentItem.Header as Product;    //Create instance object of type product 
        if (parentItem.Items.Count > 0)        //Check if the product parent item has any children 
        { 
         object child = parentItem.Items.GetItemAt(0);   //First Child object set to * during first population 
         if (child.ToString() == "*")       //If indeed it is a * 
         {       
          parentItem.Items.RemoveAt(0);      //Remove the * 

          objProd.ConsultationTypes.Load(); 
          //objProd.Name.ToList(); 

          objProd.ConsultationTypes.OrderBy(l => l.Product).ToList().ForEach(l => 
          { 
           TreeViewItem item = new TreeViewItem(); 
           item.Header = l; 
           parentItem.Items.Add(item); 

           l.Consultations.OrderBy(a => a.ConsultationType).ToList().ForEach(a => 
           { 
            TreeViewItem attrItem = new TreeViewItem(); 
            attrItem.Header = a; 
            item.Items.Add(attrItem); 
           }); 

           if (l.Consultations.Count > 0) 
            item.IsExpanded = true; 
          }); 

          if (!parentItem.IsExpanded) 
           parentItem.IsExpanded = true; 
          parentItem.IsSelected = true; 
         } 
        } 
       } 
      } 

я называю выше блок кода, нажав на корневых узлах, созданных с помощью следующего кода:

private void PopulateTreeview(SomeEntities ctx) 
     { 
      TreeViewItem rootItem = new TreeViewItem(); 
      RootItem root = new RootItem(); 
      root.Name = "Features"; 
      rootItem.Header = root.Name; 
      productTreeView.Items.Add(rootItem); 

      ctx.Products.OrderBy(o => o.Name).ToList().ForEach(d => 
      { 
       TreeViewItem item = new TreeViewItem(); 
       item.Header = d.Name; 
       item.Items.Add("*"); 
       rootItem.Items.Add(item); 
      }); 

      rootItem.IsExpanded = true; 
     } 

Ниже приводится функция, которая на самом деле отслеживает, какой был нажат узел, а затем, наконец, вызывает фактический метод ExpandLevel, который предназначен для заполнения дочерних узлов с ConsultationTypes:

private void tvProducts_Expanded(object sender, RoutedEventArgs e) 
     { 
      TreeViewItem item = (TreeViewItem)e.OriginalSource; 
      ExpandLevel(item); 
     } 

А вот отношение XAML:

<TreeView 
              x:Name="productTreeView" 
              Margin="18,0,-18,0" 
              ItemsSource="{Binding}" 
              Height="300" 
              TreeViewItem.Expanded="tvProducts_Expanded" 
              > 
             </TreeView> 
<DataTemplate DataType="{x:Type local:ConsultationType}"> 
      <StackPanel Orientation="Horizontal" Margin="0,2,0,2"> 
       <Image x:Name="Icon" Height="16" Width="16" Source="/Images/VSClass16.png" /> 
       <TextBlock Margin="2,0,0,0" VerticalAlignment="Center" Text="{Binding ProductId}" /> 
       <TextBlock VerticalAlignment="Center" Text="." /> 
       <TextBlock x:Name="Name" Margin="4,0,0,0" VerticalAlignment="Center" Text="{Binding Name}" /> 
      </StackPanel> 
     </DataTemplate 

ответ

0

я в конечном итоге делает это таким образом:

private void GetTreeViewData() 
     { 
      List<Heirachi> result = new List<Heirachi>(); 
      //get all heirachi 
      using (var c = new IWHSMacsteelEntities()) 
      { 
       result = (from p in c.Products 
          from ct in c.ConsultationTypes 
          where p.Id == ct.ProductId 
          orderby p.Id 
          select new Heirachi 
          { 
           Name = p.Name, 
           Code = ct.Code, 
           ConsTypeDesc = ct.Name 
          }).ToList(); 



      } 
      //distinct product 
      var distinctResult = result.Select(s=>s.Name).Distinct();   

      //populate parent treeview 
      TreeViewItem rootItem = new TreeViewItem(); 
      RootItem root = new RootItem(); 

      root.Name = "Features"; 
      rootItem.Header = root; 
      productTreeView.Items.Add(rootItem); 


      foreach (var dr in distinctResult) 
      { 
       TreeViewItem item = new TreeViewItem(); 
       item.Header = dr.ToString(); 
       //item.Items.Add("*"); 
       rootItem.Items.Add(item); 

       //add children 
       result.Where(s => s.Name == dr.ToString()).Select(s => s.ConsTypeDesc).ToList().ForEach(i => 
        { 
         TreeViewItem childItem = new TreeViewItem(); 
         childItem.Header = i.ToString(); 
         //item.Items.Add("*"); 
         item.Items.Add(childItem); 

        }); 

      } 
      rootItem.IsExpanded = true; 
     } 

Большое спасибо Bongolwethu за то, что помогли мне придумать это решение.

0

Вы должны использовать Явная загрузка:

var objectContext = (ctx as System.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext; 
objectContext.LoadProperty(objProd, o => o.ConsultationTypes); 

Вместо

objProd.ConsultationTypes.Load(); 

в методе "ExpandLevel"

+0

Я получаю сообщение об ошибке из-за LoadProperty от вашего ответа: Error \t \t 2 «_360ClientConfigurationPortal.IWHSMacsteelEntities» не содержит определение для «LoadProperty», а метод расширения «LoadProperty» принимающий первый аргумент типа " можно найти ConfigurationPortal.SomeEntities' (вы пропали без вести с помощью директивы или ссылка на сборку?) \t C: \ Программирование \ Source \ Workspaces \ ConfigurationPortal \ ConfigurationPortal \ MainPage.xaml.cs \t 34 ConfigurationPortal – Sizons

+0

@Sizons попробовать ' var objectContext = (ctx as System.Data.Entity.Infrastructure.IObjectContextAdapter) .ObjectContext; ', а затем' objectContext.LoadProperty (objProd, o => o.Consult ationTypes); ' – Sandeep

+0

Я попробовал это так же, и снова получил ошибку на LoadProperty. – Sizons

Смежные вопросы