Search code examples
c#xamlmaui

MAUI: Change Label.Text using DisplayPromptAsync()


I want to change the Content of a Label through the Pop-pup DisplayPromptAsync() which allows you to type text and save the text to use, but when I try to apply it does not work.

Label in XAML:

<Label Grid.Row="2" Text="UserName" x:Name="LabelName" FontAttributes="Bold" TextColor="White" HorizontalTextAlignment="Center" Margin="0,-45,0,0" FontSize="22"/>

Button in XAML:

<Button Grid.Column="1"  WidthRequest="115" HeightRequest="45" Text="Name" TextColor="White" Margin="200, 2 ,200, -274"  CornerRadius="19" Clicked="NameClicked"/>

Code-behind of Button:

private async void NameClicked(object sender, EventArgs e)
{
    var ResultName = await DisplayPromptAsync("Insira seu Nome", "Favor inserir seu Nome","Ok");

    LabelName.Text = ResultName;
}

I hoped that as soon as he kept the text in the variable could already assign and change quietly, only the code has no error is not working.


Solution

  • I create a demo and here is the code in .xaml. It works well on my side.

    <VerticalStackLayout
                Spacing="25"
                Padding="30,0"
                VerticalOptions="Center">
                
                <Label Text="UserName"  x:Name="LabelName" FontSize="22"/>
    
                <Button Clicked="NameClicked"/>
    
     </VerticalStackLayout>
    

    Here is the code in .cs file.

    private async void NameClicked(object sender, EventArgs e)
        {
            var ResultName = await DisplayPromptAsync("Insira seu Nome", "Favor inserir seu Nome", "Ok");
    
            LabelName.Text = ResultName.ToString();
        }