Stefan Chonov
Stefan Chonov

Reputation: 121

How to replace user control in cell into the Grid. WPF?

I have a Grid with 5 rows and 5 columns. I creating this Grid dynamically. Every cell contains custom user control. I would like to replace the user control dynamically with other user control at given row and column. You can see the method implementation which creates the Grid here.

My question is how to replace the user control at given row and column after the Grid is already created? Sorry if my English is bad!

Thank you in advance!

Upvotes: 1

Views: 1779

Answers (1)

Nuffin
Nuffin

Reputation: 3972

This function will probably fit your needs

public void ReplaceItemAt(Grid grid, FrameworkElement fe, int row, int col)
{
    // clear desired cell
    var items = grid.Children
        .Where(x => Grid.GetRow(x) == row && Grid.GetColumn(x) == col)
        .ToArray();
    foreach(var item in items) grid.Children.Remove(item);

    // make sure the new item is positioned correctly
    Grid.SetRow(fe, row);
    Grid.SetColumn(fe, col);

    // insert the new item into the grid
    grid.Children.Add(fe);
}

Upvotes: 3

Related Questions