简体   繁体   中英

How to add a new Label to the window when a button is pressed in WPF C#

I want to create a program that when you click the button it displays what's inside the textbox in the window as a new label

so far this is what the code looks like

XAML

<Window x:Class="firstwpfapp.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:firstwpfapp"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid Margin="-120,-142,0,0" >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0*"/>
        <ColumnDefinition Width="5*"/>
        <ColumnDefinition Width="451*"/>
    </Grid.ColumnDefinitions>
    <StackPanel x:Name="Wrapper">

    </StackPanel>

    <TextBox x:Name="input" Grid.Column="2" HorizontalAlignment="Left" Height="31" Margin="106,198,0,0" TextWrapping="Wrap" Text="Enter here" VerticalAlignment="Top" Width="166"/>
    <Button  Content="Button" Grid.Column="2" HorizontalAlignment="Left" Margin="106,234,0,0" VerticalAlignment="Top" Width="166" Height="26" Click="addTask"/>

</Grid>

C#

using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace firstwpfapp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void addTask(object sender, RoutedEventArgs e)
        {





            String val = input.GetLineText().ToString();
            Label todo = new Label();
            todo.Content = val;
            Wrapper.Children.Add(todo);



        }
    }
}

So far nothing get's added to the window when I press the button.

Does this compile? According to the documentation here ( https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.textbox.getlinetext?view=netframework-4.7.2#System_Windows_Controls_TextBox_GetLineText_System_Int32_ ) the method GetLineText() requires an integer parameter to be passed in. If you want the whole text value you could use the .Text property.

In addition you haven't defined a size/position for your StackPanel and it may not be visible.

Also GetLineText(int) already returns a string, there's no need to call .ToString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM