Вставить строки в сетку данных Silverlight - PullRequest
2 голосов
/ 04 мая 2010

Кто-нибудь знает способ внедрения строк в DataGrid Silverlight? Мне нужен способ добавить итоговые строки после каждых 6 записей. Итоги приведены для всех строк выше итоговой строки, а не только для предыдущих шести.

Я попытался сделать это с группировкой, но это показывает только итоги для группы и отображает итоговые строки над фактическими строками. Я бы предпочел использовать DataGrid для этого, если это возможно, но все решения приветствуются.

1 Ответ

1 голос
/ 05 мая 2010

Хорошо, у меня есть решение для вас; Тем не менее, он содержит в себе некоторые интересные математические кунг-фу, и поэтому я не уверен, что это лучшее решение. Однако он работает с 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 на любое значение, и оно все равно должно работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...