WPF動態建立多行多列Button
阿新 • • 發佈:2018-12-04
動態新增多行多列資料:
XAML程式碼:
<Window x:Class="GameDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:GameDemo" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded" > <Grid Name="gridBtns"> </Grid> </Window>
XAML.cs程式碼:
private void Window_Loaded(object sender, RoutedEventArgs e) { this.Title = "連連看"; //動態設定gridGame為10行10列 for (int i=0; i<10; i++) { RowDefinition rd = new RowDefinition(); gridBtns.RowDefinitions.Add(rd); ColumnDefinition cd = new ColumnDefinition(); gridBtns.ColumnDefinitions.Add(cd); } for (int i=0; i<10; i++) { for (int j=0; j<10; j++) { Button btn = new Button(); btn.Content = "btn" + i + ":" + j; Grid.SetRow(btn,i); Grid.SetColumn(btn,j); gridBtns.Children.Add(btn); } } }
執行結果