【问题标题】:Wpf How to fill a grid with label?Wpf如何用标签填充网格?
【发布时间】:2017-02-21 13:32:51
【问题描述】:

我需要你的帮助来用 WPF 中的标签填充我的网格。

想象一个 3x3 的网格。

我的代码是这样的: MainWindow.xaml.cs

private void CreationDeLaCarte()
{
    Label CaseForet = new Label();
    CaseForet.Background = Brushes.Black;
    Grille.Children.Add(CaseForet);
}

private void CreerLesCases()
{
    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            CreationDeLaCarte();
        }
    }
}   

结果:网格中只有一个单元格被涂黑。而不是我想要的所有网格。我该如何改进呢?

感谢您的回复! :)

【问题讨论】:

  • 如果网格是 3x3,为什么循环有 8 个和 10 个上限?要将标签放在正确的单元格中,您需要为每个标签设置 Grid.RowGrid.Column 属性。如果您对 MVVM 解决方案感兴趣,请查看以下问题:stackoverflow.com/questions/37145391/…
  • 感谢您的链接!是的,我看到了,这是一个例子。 :)

标签: wpf grid


【解决方案1】:

您应该在循环中设置Grid.RowGrid.Column 属性:

 private void CreationDeLaCarte(int i, int j)
{
    Label CaseForet = new Label();
    CaseForet.Background = Brushes.Black;           
    Grille.Children.Add(CaseForet);
    Grid.SetRow(CaseForet, i);
    Grid.SetColumn(CaseForet, j);
}

你的循环应该是这样的:

    for (int i = 0; i < 8; i++)
    {
        for(int j = 0; j <10; j++)
        {
            CreationDeLaCarte(i,j);
        }
    }

确保最大列数和行数与您的 Grid 一致。

【讨论】:

    【解决方案2】:

    我成功了。

    我必须输入一些参数,例如:

    private void CreationDeLaCarte(**int i, int j**)
        {Label CaseForet = new Label();
        CaseForet.Background = Brushes.Black;           
        Grille.Children.Add(CaseForet);
        **Grid.SetColumn(CaseForet, i);
        Grid.SetRow(CaseForet, j);**
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 2010-09-21
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多