Search code examples
c#xamarinxamarin.formsxamarin.androidxamarin.ios

make on button click action for first time in Xamarin (C# and xaml file)


this is my first time to start coding in mobile app (Xamarin) using C# and I'm trying to create button when I click it, Message Appear with some Information's I wrote this code in .xaml file :

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App1.MainPage">
    <ContentPage.Content>
        <StackLayout>

            <Button Text="click Me"
                VerticalOptions="CenterAndExpand"
                HorizontalOptions="Center"
                Clicked="OnButtonClicked"/>
            <Label x:Name ="lblMessage" FontSize="Large"></Label>
        </StackLayout>
    </ContentPage.Content>
 

</ContentPage>

and I wrote this in c# file :

namespace App1
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void OnButtonClicked(object sender, EventArgs e)
        {
            lblMessage.Text = "save";
        }
    }
}

The error i had it's in lblMessage variable in c# file it's :

The name 'lblMessage' does not exist in the current context

I do it from youtube channel and this is was exactly what he did, but it's worked with him and gives an error with me, any idea or help ?


Solution

  • 1.Clean your project first

    2.Rebuild it, change your XAML file properties (Build Action) from Embedded Resource to C# complier, Rebuild your project (will throw errors).

    3.Switch back your XAML file properties to Embedded Resource, Rebuild.

    Refer to this link: https://forums.xamarin.com/discussion/96447/the-name-initializecomponent-does-not-exist-in-the-current-context