First Of all please create a grid of fixed no. of rows & columns so that it would be easier to get free cells.. here is the code..
void TotalUsed()
{
TotalUsedCells = new ObservableCollection<usedcells>();
foreach (var item in HomeItems)
{
for (byte i = item.RowNumber; i < (item.RowNumber + item.RowSpan); i++)
{
for (byte j = item.ColumnNumber; j < (item.ColumnNumber + item.ColumnSpan); j++)
{
TotalUsedCells.Add(new UsedCells() { RowNo = i, ColumnNo = j });
}
}
}
}
</usedcells>
Here I have Created a collection of my UsedCells which contains only 2 properties (RowNo & ColumnNo). and each time i add a new item or expand it or reduce it add or remove from this collection. HomeItems here are the list of items, in Your case you may have your user control Later to get Free Cells...
for (byte aRow = 0; aRow <= TotalRows - 1; aRow++)
{
for (byte aCol = 0; aCol <= TotalColumns - 1; aCol++)
{
var aCells = _gdHelper.TotalUsedCells.Where(x => x.RowNo == aRow && x.ColumnNo == aCol).FirstOrDefault();
if (aCells == null)
freeCells.Add(new UsedCells() { RowNo = aRow, ColumnNo = aCol });
}
}
As I told We should have TotalRows & TotalColumns To calculate, here i have done it. & freeCells are just my another Collection of UsedCells.
Hence While placing any item i just...
if (freeCells == null || freeCells.Count == 0)
throw new Exception("THERE IS NO FREE SPACE AVAILAIBLE TO ADD ITEMS");
if (homeList.Count > freeCells.Count)
throw new Exception(string.Format("THERE IS NO FREE SPACE AVAILAIBLE, PLEASE REDUCE THE SELECTIONS TO {0}", freeCells.Count));
foreach (var h in homeList)
{
var hItem = RootHomeScreenItems.FirstOrDefault(x => x.ID == h);
var fCells = freeCells.FirstOrDefault();
hItem.RowNumber = fCells.RowNo;
hItem.ColumnNumber = fCells.ColumnNo;
freeCells.Remove(fCells);
_gdHelper.AddUsed(hItem);
hCollection.Add(hItem);
}
The AddUsed Method here Just Adds in the TotalUsedCells.
Hope You get help From This...