Bader H Al Rayyes
Bader H Al Rayyes

Reputation: 522

Binding Button.text property in the event handler

I am trying to work on Xamarin tutorial which I need to create a button and when I click it, it changes it text. Here is my XAML code:

<ViewCell>
 <StackLayout Orientation="Horizontal" Padding="5">
   <Image Source="{Binding ImageURl}"></Image>
   <StackLayout HorizontalOptions="StartAndExpand">
       <Label x:Name="ContactName" Text="{Binding Name}"></Label>
       <Label Text="{Binding Status}" TextColor="Gray"></Label>
   </StackLayout>
   <Button x:Name="mybtn" Text="Follow" Clicked="Button_Clicked"></Button>
 </StackLayout>
</ViewCell>

Here is my Code-Behind C#

public void Button_Clicked(object sender, EventArgs e)
        {
            mybtn.text = "Following";
        }

Every time I write this mybtn.text= "following", the log says Error CS0103 The name 'mybtn' does not exist in the current context MobileApp

Can someone tell me where I go wrong? is this how the bind elements should work?

Upvotes: 0

Views: 33

Answers (1)

Jason
Jason

Reputation: 89082

you can't refer to elements by name when they are contained in templates

instead, do this

public void Button_Clicked(object sender, EventArgs e)
    {
        var button = (Button)sender;
        button.text = "Following";
    }

Upvotes: 1

Related Questions