假期没事,用C#WPF画连连看的界面

xaml文件里面代码,用Grid布局:

  <Window x:Class="连连看.MainWindow"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded_1">
      <Grid Loaded="Grid_Loaded_1">
         
         <Grid Loaded="Grid_Loaded_2" Name="game"></Grid>cs
              <!--<StackPanel Name="sp1" Grid.ColumnSpan="2" Loaded="sp1_Loaded" MouseEnter="sp1_MouseEnter"></StackPanel>-->
      </Grid>
 </Window>

xaml.cs文件里面的代码,加载窗体的时候加载10行10列,里面画按钮,按钮的Content属性显示图片:

 private void Grid_Loaded_2(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i <= 9;i++ )
            {
                /*逻辑上划分10行10列*/
                ColumnDefinition lei = new ColumnDefinition();
                game.ColumnDefinitions.Add(lei);
                RowDefinition hang = new RowDefinition();
                game.RowDefinitions.Add(hang);
            }
            Random ran = new Random();//实例化一个随机数,为遍历图片的名字
            for (int i = 0; i <= 9; i++)
            {
                for (int j = 0; j <= 9; j++)
                {
                    Image img = new Image();//实例化图片控件
                    int imgName = ran.Next(0, 10);//int类型数据>=0  <10
                    img.Source = new BitmapImage(new Uri("tupian/" + imgName + ".png", UriKind.Relative));//获取图片地址
                    Button but = new Button();
                    /*给按钮规定位置*/
                    but.Content = img;
                    Grid.SetRow(but, j);
                    Grid.SetColumn(but, i);//完成了按钮属性的定义
                   
                    game.Children.Add(but);//按钮画到窗体里面
                    
                    
                }
            }
        }

posted @ 2019-01-17 11:00  紫系流月  阅读(305)  评论(0编辑  收藏  举报