2010-05-03 6 views
2

Silverlight DataGrid에 행을 삽입하는 방법을 알고있는 사람이 있습니까? 매 6 개 항목마다 합계 행을 추가하는 방법이 필요합니다. 합계는 이전 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