2015-09-04 105 views
2

我对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); 
      } 
     } 
    } 
} 
+0

你能告诉我们xaml吗?我怀疑窗户已经有了一个孩子。 – dnr3

+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> 
+0

这个伎俩!非常感谢! – user3134763

+0

你可以upvote并接受它为答案,因为它解决了你的问题 –