我对C#很陌生,现在只是在玩弄东西。我试图在窗口中用按钮或标签在窗口中创建一个网格。我偶然发现了这个问题How to create a dynamic grid containing panels使用面板创建动态网格
我一直在努力,实现这一收到一条错误消息,
:在this.addchild线“异常抛出 PresentationFramework.dll‘System.InvalidOperationException’”。我已经附上了 以下的内容。
*请注意,这不是功课,我只是玩弄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吗?我怀疑窗户已经有了一个孩子。 – dnr3
例外*真的*不包含消息吗?如果是这样,你可以发布它吗? –