2010-05-03 59 views
2

有誰知道將行注入Silverlight DataGrid的方法嗎?我需要一種方法在每6個條目之後添加總計行。總數適用於彙總行之上的所有行,而不僅僅是前六行。將行注入Silverlight DataGrid

我試着做分組,但只顯示該組的總數,並顯示實際行上方的總計行數。如果可能,我寧願爲此使用DataGrid,但所有解決方案都是受歡迎的。

回答

1

好的,我有一個解決方案給你;然而,它包含了一些時髦的數學功夫,所以我不確定它是否是最好的解決方案。但是,它確實可以使用DataGrid。

public void PopulateAndSum() 
    { 

     //Ugly Math Kung Fu starts here 
     //Get the number of rows in the collection 
     int rowCount = Items.Count; 

     //Here you specify after how many rows should the summation occur 
     int numRowsToSum = 6; 

     //Now the idea is to loop through the collection the same number of times 
     //As you would be inserting summation rows into the collection 
     //To calculate the maximum number of times you should circulate you 
     //divide through the number of rows and ceil the result. Make sure 
     //divide by a double or at least cast one of them to a double so you do 
     //not get integer division 
     for (int i = 0; i < Math.Ceiling(((double)rowCount)/numRowsToSum); i++) 
     { 
      //Now you want to calculate the position where you need to insert the the new entry 
      int index = 0; 

      //Check whether you are still in the bounds of the array or whether you have actually reached the last element 
      //in the array. This should always be the case if your collection contains a multiple of numRowsToSum 
      if (numRowsToSum + i * (numRowsToSum) <= rowCount) 
      { 
       //The index starts at numRowsToSum because you start the collection indexing at 0 
       //From there you jump the next index and add one to take into account that you inserted a new element 
       index = numRowsToSum + i*(numRowsToSum + 1); 
      } 
      else 
      { 
       //If your collection contains a number of elements that are not a precise multiple of numRowsToSum 
       //then you have to have a special condition where you calculate the index for the last few elements 
       //Here you need to jump back to the previous index and add the number of elements left in the collection 
       //You also have to add 1 to take into account that you are adding an extra row. 
       index = numRowsToSum + (i - 1) * (numRowsToSum + 1) + 1 + rowCount % numRowsToSum; 
      } 

      //Now you sum all the rows before the index 

      int sum = 0; 
      for (int j = 0; j < index; j++) 
      { 
       //If you want to add the previous totals to the sum comment the next part out 
       if ((j - numRowsToSum) % (numRowsToSum + 1) == 0) 
        continue; 

       sum += Items[j].Value; 
      } 

      //Now add the entry 
      Items.Insert(index, new Info() { Name = "Total", Value = sum }); 
     } 
    } 

Items是一個ObservableCollection和Info僅僅是一個測試類我創建。我非常徹底地評論了代碼。它比您的要求更通用,因爲您可以將numRowsToSum更改爲任何值,並且它仍然可以正常工作。

+0

我希望找到一個解決方案,不需要直接添加到綁定的集合,但我最終做了一些非常相似的事情。謝謝你的幫助。 – Stephan 2010-05-05 14:04:09