可以自定义一个UIElement
public MainWindow() { InitializeComponent(); Grid grid = new Grid(); for (int i = 0; i < 10; i++) { ColumnDefinition columnDefinition = new ColumnDefinition(); grid.ColumnDefinitions.Add(columnDefinition); } for (int i = 0; i < 4; i++) { RowDefinition rowDefinition = new RowDefinition(); grid.RowDefinitions.Add(rowDefinition); } for (int i = 0; i < grid.ColumnDefinitions.Count; i++) { for (int j = 0; j < grid.RowDefinitions.Count; j++) { Rectangle rectangle = new Rectangle(); rectangle.Tag = i + ":" + j; rectangle.Stroke = new SolidColorBrush(Colors.Black); rectangle.StrokeThickness = 1; rectangle.HorizontalAlignment = HorizontalAlignment.Stretch; rectangle.VerticalAlignment = VerticalAlignment.Stretch; Grid.SetColumn(rectangle, i); Grid.SetRow(rectangle, j); grid.Children.Add(rectangle); } } //把第二列的第三行的矩形的背景设为红色 foreach (Rectangle elemnet in grid.Children) { if (elemnet.Tag.ToString() == "1:2") { elemnet.Fill = new SolidColorBrush(Colors.Red); } } }