[英]Unable to add Rows dynamically to a Grid in WPF
我想将RowDefinitions添加到名为notices的网格中。 我可以获取数据库中的行数并重复这些次数,但是我无法将控件添加到行中。
正在创建该行,但未添加StackPanel。 我的代码想要动态创建行,并在该行上创建一个StackPanel,并在StackPanel上创建标签和图像。 在.xaml文件中,我仅添加了网格。
如何将带有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());
}
您必须使用Grid.SetRow和Grid.SetColumn将附加属性( Grid.Row
和Grid.Column
)设置为控件。
之后,您需要像这样向网格添加控件:
nameOfYourGrid.Children.Add(nameOfYourControl);
另外,您的代码中有一些有趣的行:
"Date_Time".ToString(); ;
为什么将string
转换为string
?
多数字段可以移到foreach
区域的内部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.