我是C#的新手,现在只是玩弄东西。我试图在窗口中创建一个带有按钮或标签的网格。我偶然发现了这个问题How to create a dynamic grid containing panels
我试图实现这个收到错误说明
“抛出异常:'System.InvalidOperationException'中 PresentationFramework.dll“在this.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);
}
}
}
}
答案 0 :(得分:1)
只需从 XAML
中删除网格部分即可如果你的代码看起来像这样
<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>