【问题标题】:Creating a dynamic grid with panels使用面板创建动态网格
【发布时间】:2015-09-04 02:32:00
【问题描述】:

我对 C# 非常陌生,目前只是在玩弄一些东西。我试图在一个带有按钮或标签的窗口中创建一个网格。我偶然发现了这个问题How to create a dynamic grid containing panels

我已尝试实施此操作,但收到错误说明

“抛出异常:'System.InvalidOperationException' in 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);
            }
        }
    }
}

【问题讨论】:

  • 你能给我们看看 xaml 吗?我怀疑窗口已经有了一个孩子。
  • 异常真的不包含消息吗?如果有,可以发一下吗?

标签: c# wpf


【解决方案1】:

只需从 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>

【讨论】:

  • 您可以投票并接受它作为答案,因为它解决了您的问题
猜你喜欢
  • 2012-07-24
  • 2023-03-09
  • 1970-01-01
  • 2012-06-15
  • 2019-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多