2017-11-11 132 views
-1

我有两个表格Equipment and Components。每个设备由1个或多个组件组成。现在我有一个显示设备的数据网格,以及来自数据库中View的相关属性。在WPF中选择数据网格行时,在数据网格中显示相关表中的数据

我想要的是在同一窗口中有第二个数据网格,它将显示数据网格中包含的选定设备的组件。

到目前为止,我知道我可以使用SelectedItem属性获取选定行:

Equipment eq= (Equipment)myDataGrid.SelectedItem; 

但是,当应此代码运行?我正在使用EF将我的数据库实体映射到CLR对象,其中也包含了组件及其关系表。

当用户在设备中选择一行时,当然我需要用新信息刷新组件数据网格,我可以这样做。

myGrid.ItemsSource = myDataSource; 

我该如何开始解决这个问题?

我正在使用一个视图,该视图包含来自我的设备数据网格中的3个不同表格的数据,因此设置为数据网格ItemsSource的表格与组件表格没有直接关系。

回答

0

我固定它通过使用获得的组件和插入他们到数据网格时对设备数据网格SelectionChanged事件被称为:

private void EquipDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) 
     { 
      try 
      { 
       var row_list = GetDataGridRows(EquipDataGrid); 
       foreach (DataGridRow single_row in row_list) 
       { 
        if (single_row.IsSelected == true) 
        { 
         EquipmentView selectedEquipment = (EquipmentView)EquipDataGrid.SelectedItem; 
         using (wiki_nolek_dk_dbEntities db = new wiki_nolek_dk_dbEntities()) 
         { 
          db.Configuration.LazyLoadingEnabled = true; 
          var equipmentRelation = db.EquipmentComponents.Where(c => c.EquipmentID == selectedEquipment.EquipmentId); 
          var componentsForEquipment = new List<Component>(); 
          foreach (var row in equipmentRelation) 
          { 
           var component = db.Components.FirstOrDefault(c => c.ComponentId == row.ComponentID); 
           componentsForEquipment.Add(component); 
          } 
          CompDataGrid.ItemsSource = componentsForEquipment; 
         } 
        } 
       } 

      } 
      catch 
      { 
       MessageBox.Show("Det valgte udstyr eksisterer ikke."); 
      } 
     } 
0

我已经修改了自己的答复的代码删除无用foreach环。我不知道wiki_nolek_dk_dbEntities是如何工作的,但我还将ToList()添加到任何db查询结果以确保结果是List而不是IQueryable

 private void EquipDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     try 
     { 
      EquipmentView selectedEquipment = (EquipmentView)EquipDataGrid.SelectedItem; 
      using (wiki_nolek_dk_dbEntities db = new wiki_nolek_dk_dbEntities()) 
      { 
       db.Configuration.LazyLoadingEnabled = true; 

       var equipmentRelationComponentIds = 
        db.EquipmentComponents 
         .Where(e => e.EquipmentID == selectedEquipment.EquipmentId) 
         .Select(e => e.ComponentId) 
         .ToList(); 

       var componentsForEquipment = 
        db.Components 
         .Where(c => equipmentRelationComponentIds.Contains(c.ComponentId)) 
         .ToList(); 

       CompDataGrid.ItemsSource = componentsForEquipment; 
      } 
     } 
     catch 
     { 
      MessageBox.Show("Det valgte udstyr eksisterer ikke."); 
     } 
    }