WPF中任何的的一个控件都是一个类,它们都可以通过代码将其对象new出来,还可以通过代码给其对象赋值。如下面的例子:

Image img=new Image();

//代码给Source属性赋值

img.Source=new BitmapImage(new Uri("1.jpg",UriKind.Relative));   //Uri中第一个参数表示图片的路径,第二个参数表示图片路径的类型,有三种,如Absolute(绝对路径)、                        Relative(相对路径)、RelativeorAbsolute(两者中的一种)。

grid.Children.Add(img);   //将图片加载到Grid中

在WPF中动态使用图片和按钮

下面的一段代码是向Grid中动态生成十行十列的表格,并在表格中插入100个Button

 1 private void Window_Loaded(object sender, RoutedEventArgs e)
 2         {
 3             for (int i = 0; i < 10;i++)
 4             {
 5                 ColumnDefinition colDf = new ColumnDefinition();
 6                 RowDefinition rowDf = new RowDefinition();
 7                 gridGame.ColumnDefinitions.Add(colDf);
 8                 gridGame.RowDefinitions.Add(rowDf);
 9             }
10             for (int i = 0; i < 10;i++ )
11             {
12                 for (int j = 0; j < 10;j++ )
13                 {
14                     Button btn = new Button();//动态创建控件对象
15                     btn.Content = i + "," + j;
//通过代码修改控件的Grid.Row属性
16 Grid.SetRow(btn, i); 17 Grid.SetColumn(btn, j); 18 gridGame.Children.Add(btn);//把控件加入容器父控件的Children 19 } 20 } 21 }

在WPF中动态使用图片和按钮

相关文章:

  • 2022-12-23
  • 2022-01-10
  • 2021-08-07
  • 2021-11-13
  • 2022-02-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-20
  • 2021-12-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案