Mirwais
Mirwais

Reputation: 131

How can I access x:name in the code behind in Xamarin?

So I have a MasterDetails setup and what I want to achieve is the following: If I select an Item in the Menu (MasterView), I see its results (DetailsView). This DetailsView is a ListView with ViewCells. So far so good. Now I want to navigate into the details of the DetailsPage content. Let me show you the code of this:

XAML - AssignmentListPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App.Views.AssignmentListPage"
         Title="Opdrachten">
<ListView x:Name="AssignmentsListView" Margin="20">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Padding="20,0,0,0" HorizontalOptions="StartAndExpand" Orientation="Horizontal">
                    <Label x:Name="myAssignments" Text="{Binding Title}" VerticalTextAlignment="Center" />
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

And the code-behind file:

C# - AssignmentListPage.xaml.cs

public partial class AssignmentListPage : ContentPage
    {
        public AssignmentListPage ()
        {
            InitializeComponent ();

            NavigateDetails();
        }

        protected override async void OnAppearing()
        {
            base.OnAppearing();

            AssignmentsListView.ItemsSource = await 
    App.AssignmentManager.GetAssignmentsAsync();

        }

        public void NavigateDetails()
        {
            var tap = new TapGestureRecognizer();

            tap.Tapped += (s, e) => OnLabelClickedAsync();

            myAssignments.GestureRecognizers.Add(tap);


        }

        public async Task OnLabelClickedAsync()
        {
            await Navigation.PushAsync(new AssignmentDetailsPage());
        }

    }

The problem is that myAssignments in the code-behind gives me a "Cannot resolve symbol ... " error.

I've tried the following without success:

In the NavigateDetails() function I've replaced myAssignments with:

var asd = this.FindByName<Label>("myAssignments");

asd.GestureRecognizers.Add(tap);

I have also tried using this, so like:

this.myAssignments.GestureRecognizers.Add(tap);

Can you guys tell me what I am doing wrong? I cannot access the label.

Upvotes: 0

Views: 5217

Answers (1)

Jason
Jason

Reputation: 89214

add a gesture recognizer in XAML

<Label x:Name="myAssignments" Text="{Binding Title}" VerticalTextAlignment="Center" >
  <Label.GestureRecognizers>
    <TapGestureRecognizer Tapped="OnLabelClickedAsync" />
  </Label.GestureRecognizers>
</Label>

Upvotes: 1

Related Questions