如何在WPF中点击一个按钮创建多个按钮?

问题描述 投票:0回答:0

希望每次点击“创建按钮”按钮时,都会创建一个新的按钮,每列最多8个按钮,然后继续点击“创建按钮”按钮,就会创建新的按钮在第二列,依此类推,我想要达到的效果是这样的: enter image description here

但是目前我能力有限,大概是这样的: enter image description here

这是我的MainWindow.xaml

<Window x:Class="Helloone.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:Helloone"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid x:Name="grid" VerticalAlignment="Top" Margin="10">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Button x:Name="button1" Content="Create Button" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Button1_Click" Grid.Row="0" Grid.Column="0"/>
    </Grid>
</Window>

这是我的MainWindow.xaml.cs

namespace Helloone
{
 /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private int buttonCount = 1;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            // Create a new button
            Button button = new Button();
            button.Content = "Button " + buttonCount.ToString();

            button.HorizontalAlignment = HorizontalAlignment.Left;
            button.VerticalAlignment = VerticalAlignment.Top;
            button.Margin = new Thickness(10);

            // Add the new button to the Grid
            int row = (buttonCount - 1) / 3 + 1;
            int column = (buttonCount - 1) % 3;
            grid.Children.Add(button);
            Grid.SetRow(button, row);
            Grid.SetColumn(button, column);

            // Increment the button count
            buttonCount++;
        }
    }
}
c# .net wpf xaml button
© www.soinside.com 2019 - 2024. All rights reserved.