[英]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.