【发布时间】: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