如何将单元格中的用户控件替换到网格中.WPF

本文关键字:替换 网格 WPF 控件 单元格 用户 | 更新日期: 2023-09-27 18:19:46

我有一个Grid,它有5行5列。我动态地创建了这个Grid。每个单元格都包含自定义用户控件。我想在给定的行和列中用其他用户控件动态地替换用户控件。您可以在这里看到创建Grid的方法实现。

我的问题是,在创建了Grid之后,如何替换给定行和列的用户控件?对不起,如果我的英语不好!

提前谢谢!

如何将单元格中的用户控件替换到网格中.WPF

此功能可能适合您的需求

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);
}