创建带有面板的动态网格
本文关键字:动态 网格 创建 | 更新日期: 2023-09-27 18:11:18
我对c#非常陌生,目前只是在玩一些东西。我试图在一个窗口中创建一个带有按钮或标签的网格。如何创建包含面板的动态网格
我已经尝试实现这个收到一个错误声明
"抛出异常:'System. 'InvalidOperationException"PresentationFramework.dll"。addchild线。我已经附上
*注意,这不是家庭作业,我只是玩玩来熟悉一下c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Grid grid1;
public MainWindow()
{
InitializeComponent();
int cellCount = 14;
int numCols = 3;
int numRows = (cellCount + 1) / numCols;
grid1 = new Grid();
this.AddChild(grid1);
for (int i = 0; i < numCols; ++i)
this.grid1.ColumnDefinitions.Add(new ColumnDefinition());
for (int i = 0; i < numRows; ++i)
this.grid1.RowDefinitions.Add(new RowDefinition());
foreach (var g in this.grid1.RowDefinitions)
{
g.Height = new GridLength(100);
}
foreach (var g in grid1.ColumnDefinitions)
{
g.Width = new GridLength(100);
}
for (int i = 0; i < cellCount; ++i)
{
int idx = grid1.Children.Add(new Label());
Label x = grid1.Children[idx] as Label;
x.Content = "Cell " + i;
x.SetValue(Grid.RowProperty, i / numCols);
x.SetValue(Grid.ColumnProperty, i % numCols);
}
}
}
}
从XAML中删除Grid部分
如果你的代码看起来像这样
<Window x:Class="NameSpace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525">
<Grid></Grid>
</Window>
它应该看起来像
<Window x:Class="NameSpace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525">
</Window>