如何在Xamarin中的后面代码中访问x:name?

时间:2019-01-11 14:21:47

标签: c# xaml xamarin

所以我有一个MasterDetails设置,我想要实现的目标如下: 如果在菜单(MasterView)中选择一个项目,则会看到其结果(DetailsView)。 此DetailsView是具有ViewCells的ListView。到目前为止,一切都很好。 现在,我想导航到DetailsPage内容的详细信息。 让我向您展示此代码:

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>

以及代码隐藏文件:

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());
        }

    }

问题是,后面的代码中的myAssignments给了我一个“无法解析符号...”错误。

我尝试了以下操作但未成功:

NavigateDetails()函数中,我将myAssignments替换为:

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

asd.GestureRecognizers.Add(tap);

我还尝试使用this,例如:

this.myAssignments.GestureRecognizers.Add(tap);

你们能告诉我我做错了吗?我无法访问标签。

1 个答案:

答案 0 :(得分:2)

在XAML中添加手势识别器

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