Search code examples
c#xamlbuttonlabel

WPF .NET 5 (XAML) Add some labels when i press button


I'm new. I'm learning C# .NET 5. I want to create in XAML dynamic Labels when i press add_button the labels appears in the new line under. I'm using Visual Studio 2022. I dont know what to write in MainWindow.xaml.cs.

Thanks for some advice.


Solution

  • You can use Button click event. In the event you can add some labels on a StackPanel. StackPanel will help when you add something new it will be under the last one.

    In XAML:

    <Window x:Class="DemoTryThings.MainWindow"
        xmlns:local="clr-namespace:DemoTryThings"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
        WindowStartupLocation="CenterScreen">
    
    <!--Main Grid!-->
    <Grid Margin="10">
    
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
    
        <StackPanel Grid.Row="0"
                    x:Name="LabelStackPanel"/>
    
        <Button Grid.Row="1"
                Height="30"
                Content="Add Label"
                Click="ButtonBase_OnClick"/>
    
    </Grid>
    

    In cs file:

    public partial class MainWindow : Window
    {
    
        public MainWindow()
        {
            InitializeComponent();
        }
    
        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            LabelStackPanel.Children.Add(new Label { Content = "Hi this add with button click!" });
        }
    }
    

    And result: enter image description here