1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Windows; 6 using System.Windows.Controls; 7 using System.Windows.Data; 8 using System.Windows.Documents; 9 using System.Windows.Input; 10 using System.Windows.Media; 11 using System.Windows.Media.Imaging; 12 using System.Windows.Navigation; 13 using System.Windows.Shapes; 14 15 namespace 连连看 16 { 17 /// <summary> 18 /// MainWindow.xaml 的交互逻辑 19 /// </summary> 20 public partial class MainWindow : Window 21 { 22 public MainWindow() 23 { 24 InitializeComponent(); 25 } 26 27 private void Window_Loaded(object sender, RoutedEventArgs e) 28 { 29 Random r = new Random(); 30 for (int i = 0; i < 10; i++) 31 { 32 //动态生成10x10格子 33 //注意,这里不需要嵌套循环!!不然只在第一个格子里有100个图片! 34 RowDefinition rowDef = new RowDefinition(); 35 gridGame.RowDefinitions.Add(rowDef); 36 ColumnDefinition colDef = new ColumnDefinition(); 37 gridGame.ColumnDefinitions.Add(colDef); 38 } 39 for (int i = 0; i < 10; i++) 40 { 41 for (int j = 0; j < 10; j++) 42 { 43 int n = r.Next(10); 44 //下面注释的是使用button控件 45 //Button btn = new Button(); 46 //btn.Content = i + "," + j; 47 //Grid.SetRow(btn,i); 48 //Grid.SetColumn(btn,j); 49 //gridGame.Children.Add(btn); 50 //下面是用的是image控件 51 Image img = new Image(); 52 //image的路径需要如下的方法定义 53 img.Source = new BitmapImage(new Uri(n + ".jpg", UriKind.Relative)); 54 //Console.WriteLine("{0}.jpg {1}行 {2}列",n,i,j); 55 Grid.SetRow(img, i); 56 Grid.SetColumn(img, j); 57 gridGame.Children.Add(img); 58 } 59 } 60 } 61 } 62 }