【问题标题】:Unable to add Rows dynamically to a Grid in WPF无法将行动态添加到 WPF 中的网格
【发布时间】:2015-09-27 10:03:18
【问题描述】:

我想将 RowDefinitions 添加到名为 notices 的网格中。我可以获得数据库中的行数并迭代这些次数,但我无法将控件添加到一行。

正在创建行,但未添加 StackPanel。我的代码想要动态地创建行,并创建一个 StackPanel 和一个标签和图像。在 .xaml 文件中,我只添加了 Grid。

如何将带有 StackPanel 的行添加到网格中?

这是我的代码:

    StackPanel sp;
    Label dt_label;
    Image img;
    BitmapImage bitmap;
    string col1=null,  col2 = "Picture_Path";
    string Picture_Path=null;
    RowDefinition gridRow1;
    DateTime time;

    for (int row_num = 0; row_num < No_Of_Rows; row_num++)
    { 
        DataRow row = dt1.Rows[row_num];
        foreach (object item in row.ItemArray)
        {
            gridRow1 = new RowDefinition();

            sp = new StackPanel();

            sp.Background = new SolidColorBrush(Colors.Yellow);
            col1 = "Date_Time".ToString(); ;
            time = DateTime.Parse(dt1.Rows[row_num][col1].ToString());

            dt_label = new Label();
            dt_label.Content = time;

            Picture_Path = dt1.Rows[row_num][col2].ToString();

            img = new Image();

            bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.UriSource = new Uri(Picture_Path, UriKind.Relative);
            bitmap.EndInit();
            img.Source = bitmap;

            img.Height = 100;
            img.Width = 100;

            sp.Children.Add(dt_label); 
            sp.Children.Add(img);
            notices.RowDefinitions.Add(gridRow1);
            break;
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show("ERROR \n" + ex.ToString());
}

【问题讨论】:

  • 删除所有代码并使用数据绑定。

标签: c# wpf grid stackpanel


【解决方案1】:

您必须使用Grid.SetRowGrid.SetColumn 为控件设置附加属性(Grid.RowGrid.Column)。

在此之后,您需要像这样向网格添加控件:

nameOfYourGrid.Children.Add(nameOfYourControl);

另外,您的代码中有一些有趣的行:

"Date_Time".ToString(); ;

为什么要将string 转换为string

大部分字段可以移动到内部foreach 范围内。

【讨论】:

    猜你喜欢
    • 2016-04-21
    • 2016-03-12
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    相关资源
    最近更新 更多