Xamarin: 当前上下文中不存在名称为'x'的变量

4

我是Xamarin开发的新手,希望这个看似简单的问题有一个快速的解决办法。

我的环境

  • Mac上的Xamarin Studio社区版6.1.3(版本19)
  • Xamarin.Android 7.0.2.42
  • Xamarin.Ios 10.3.1.7
  • Xcode 8.2.1
  • Mac OSX 10.12.1

我的问题

我从Visual Studio Online repo得到了一个现有的xaml文件。我为标签控件添加了一个x:name属性,叫做lblSearchText,以便在代码后台中访问它。通过xaml代码后台,我可以按名称添加此控件,没有任何问题。然而,在编译时出现以下错误:

当前上下文中不存在名称'lblSearchText'

我已经确认了以下内容:

  • XAML文件上的Build ActionEmbeddedResource
  • XAML文件上的Custom Tool属性是MSBuild:UpdateDesignTimeXaml

我的XAML编辑:添加完整的XAML

<?xml version="1.0" encoding="UTF-8" ?>
<common:ContentPage x:Class="MyApp.SearchAuthenticatedPage"
                    xmlns="http://xamarin.com/schemas/2014/forms"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                    xmlns:common="clr-namespace:MyApp.Common;assembly=MyApp.Common"
                    xmlns:commonView="clr-namespace:MyApp.Common.Views;assembly=MyApp.Common"
                    xmlns:help="clr-namespace:MyApp.Helpers;assembly=MyApp"
                    xmlns:helpersCommon="clr-namespace:MyApp.Helpers;assembly=MyApp.Common"
                    xmlns:local="clr-namespace:MyApp;assembly=MyApp"
                    xmlns:sty="clr-namespace:MyApp.Styles;assembly=MyApp">
    <common:ContentPage.Resources>
        <ResourceDictionary>
            <local:DistanceToStringConverter x:Key="DistanceToString" />
            <local:StringToHeaderConverter x:Key="StringToHeader" />
            <local:StringToUpperConverter x:Key="StringToUpper" />
            <local:IsFavoriteToBackgroundColorConverter x:Key="IsFavoriteToBackgroundColor" />
        </ResourceDictionary>
    </common:ContentPage.Resources>
    <RelativeLayout BackgroundColor="White" Padding="0">
        <common:SearchBar x:Name="searchBar"
                          Title="{helpersCommon:Translate searchBarText}"
                          ClickCommand="{Binding SearchCommand}"
                          RelativeLayout.HeightConstraint="{ConstraintExpression Type=Constant, Constant=50}"
                          RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}"
                          RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=X}"
                          RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y}" />

        <AbsoluteLayout IsVisible="{Binding IsMapVisible}"
                        RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Constant=-50}"
                        RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}"
                        RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=X}"
                        RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Constant=50}">
            <commonView:MapView x:Name="map"
                                WidthRequest="500"
                                HeightRequest="500"
                                VerticalOptions="FillAndExpand"
                                AbsoluteLayout.LayoutBounds="1,1,1,1"
                                AbsoluteLayout.LayoutFlags="All"
                                DirectionLocation="{ Binding DirectionLocation}"
                                IsVisible="{Binding IsMapVisible}"
                                Location="{Binding CurrentLocation}"
                                ShowDirection="{ Binding IsShowingDirection}"
                                Source="{Binding GetMapSource}"
                                ZoomToLocation="true" />
            <Button x:Name="getDirectionButton"
                    AbsoluteLayout.LayoutBounds=".28,.33,100,30"
                    AbsoluteLayout.LayoutFlags="PositionProportional"
                    BackgroundColor="Transparent"
                    Text="" />
            <Button x:Name="storeDetailsButton"
                    AbsoluteLayout.LayoutBounds=".70,.33,100,30"
                    AbsoluteLayout.LayoutFlags="PositionProportional"
                    BackgroundColor="Transparent"
                    IsVisible="false"
                    Text="" />
            <Button x:Name="phoneButton"
                    AbsoluteLayout.LayoutBounds=".28,.27,100,20"
                    AbsoluteLayout.LayoutFlags="PositionProportional"
                    BackgroundColor="Transparent"
                    Text="" />
        </AbsoluteLayout>
        <ListView x:Name="list"
                  HeightRequest="300"
                  CachingStrategy="RetainElement"
                  Footer="{Binding .}"
                  HasUnevenRows="true"
                  IsGroupingEnabled="true"
                  IsVisible="{Binding IsListVisible}"
                  ItemsSource="{Binding FinalSearchResult}"
                  RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Constant=-47}"
                  RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width}"
                  RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Property=X}"
                  RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Y, Constant=47}"
                  SeparatorColor="Transparent"
                  SeparatorVisibility="None">
            <ListView.FooterTemplate>
                <DataTemplate>
                    <ContentView>
                        <Label x:Name="lblSearchText" <!--- My Control --->
                               Margin="13, 10"
                               HorizontalOptions="Center"
                               IsVisible="{Binding IsEmpty}"
                               Style="{x:Static sty:Styles.PatientListBigLabelStyle}"
                               Text="{helpersCommon:Translate searchText}"
                               VerticalTextAlignment="Center" />
                    </ContentView>
                </DataTemplate>
            </ListView.FooterTemplate>
            <ListView.GroupHeaderTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout BackgroundColor="{Binding Favorite, Converter={StaticResource IsFavoriteToBackgroundColor}}" Padding="13,15">
                            <Label Style="{x:Static sty:Styles.DarkLabelStyle}" Text="{Binding GroupName}" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.GroupHeaderTemplate>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid BackgroundColor="{Binding IsFavorite, Converter={StaticResource IsFavoriteToBackgroundColor}}"
                              Padding="13,16"
                              RowSpacing="0">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*" />
                                <RowDefinition Height="5" />
                                <RowDefinition Height="Auto" />
                                <RowDefinition Height="Auto" />
                                <RowDefinition Height="35" />
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="30" />
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="100" />
                            </Grid.ColumnDefinitions>
                            <commonView:FavoriteButton Grid.Row="0"
                                                       Grid.Column="0"
                                                       Margin="0,0,7,0"
                                                       ClickCommand="{Binding FavoriteChangedCommand}"
                                                       IsFavorite="{Binding IsFavorite}"
                                                       Style="{x:Static sty:Styles.FavoriteButtonStyle}" />

                            <Label Grid.Row="0"
                                   Grid.Column="1"
                                   FontSize="{x:Static sty:Styles.VeryLargeFontSize}"
                                   Style="{x:Static sty:Styles.DarkBoldLabelStyle}"
                                   Text="{Binding ShoppingCenterName}" />
                            <Label Grid.Row="0"
                                   Grid.Column="2"
                                   FontSize="{x:Static sty:Styles.VeryLargeFontSize}"
                                   Style="{x:Static sty:Styles.DarkBoldRightLabelStyle}"
                                   Text="{Binding DistanceInMilesFromLocation, Converter={StaticResource DistanceToString}}" />
                            <Label Grid.Row="2"
                                   Grid.Column="1"
                                   IsVisible="{Binding IsAddressVisible}"
                                   Style="{x:Static sty:Styles.DarkLabelStyle}"
                                   Text="{Binding Address}" />
                            <commonView:UnderlinedButton Grid.Row="2"
                                                         Grid.RowSpan="3"
                                                         Grid.Column="2"
                                                         HeightRequest="35"
                                                         Command="{Binding ShowDetailCommand}"
                                                         IsVisible="{Binding IsNotSomeMode}"
                                                         Style="{x:Static sty:Styles.ListUnderlinedButtonStyle}"
                                                         Text="{helpersCommon:Translate detailButtonText}"
                                                         TextAligment="TopRight" />
                            <Label Grid.Row="3"
                                   Grid.Column="1"
                                   VerticalOptions="Start"
                                   IsVisible="{Binding IsAddressVisible}"
                                   Style="{x:Static sty:Styles.DarkLabelStyle}"
                                   Text="{Binding Address2}" />
                            <commonView:UnderlinedButton Grid.Row="4"
                                                         Grid.Column="1"
                                                         HeightRequest="35"
                                                         HorizontalOptions="StartAndExpand"
                                                         Command="{Binding CallCommand}"
                                                         Style="{x:Static sty:Styles.ListUnderlinedButtonStyle}"
                                                         Text="{Binding Phone}"
                                                         TextAligment="TopLeft" />
                            <commonView:ExtendedButton Grid.Row="4"
                                                       Grid.RowSpan="2"
                                                       Grid.Column="2"
                                                       HorizontalOptions="End"
                                                       VerticalOptions="Center"
                                                       Command="{Binding SomeCommand}"
                                                       IsVisible="{Binding IsSomeMode}"
                                                       Style="{x:Static sty:Styles.ActionButtonStyle}"
                                                       Text="{helpersCommon:Translate ListSomeButtonText}">
                                <commonView:ExtendedButton.FontSize>
                                    <OnPlatform x:TypeArguments="x:Double"
                                                Android="11"
                                                iOS="13" />
                                </commonView:ExtendedButton.FontSize>
                            </commonView:ExtendedButton>
                           </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </RelativeLayout>
</common:ContentPage>

我的代码背后 编辑 - 添加完整的代码

using System.Linq;
using Xamarin.Forms;
using static MyApp.Helpers.UIHelper;

namespace MyApp
{
    public partial class SearchAuthenticatedPage : global::MyApp.Common.ContentPage
    {
        public SearchAuthenticatedPage()
        {
            InitializeComponent();
            lblSearchText.Text = "hello world!";
        }

        public bool IsMapShowing { get; set; }

        protected override void OnBindingContextChanged()
        {
            base.OnBindingContextChanged();
            var vm = BindingContext as BaseListViewModel;
            if (vm != null) {
                if (!ToolbarItems.Any()) {
                    SetSwitchToolbarItem();
                }
                vm.SetSwitchToolbarItem = SetSwitchToolbarItem; 
            }
            getDirectionButton.IsVisible = false;
            storeDetailsButton.IsVisible = false;
            phoneButton.IsVisible = false;

            map.CalloutShownCommand = new Command(OnShowCallout);
            map.CalloutHidedCommand = new Command(OnHideCallout);
        }

        void OnHideCallout()
        {
            if (Device.OS == TargetPlatform.iOS) {
                return;
            }
            getDirectionButton.IsVisible = false;
            phoneButton.IsVisible = false;
        }

        void OnShowCallout()
        {
            if (Device.OS == TargetPlatform.iOS) {
                return;
            }
            getDirectionButton.Command = map.ShowDirectionsCommand;
            phoneButton.Command = map.PhoneCallCommand;
            getDirectionButton.IsVisible = true;
            phoneButton.IsVisible = true;
        }

        public void SetSwitchToolbarItem(bool isMapClicked = false)
        {
            var switchCommand = (BindingContext as BaseListViewModel)?.ChangeViewCommand;
            var switchItem = ToolbarItems.FirstOrDefault(i => i.Priority == 0);
            if (switchItem != null) {
                switchItem.Text = isMapClicked ? Localize("titleListView") : Localize("titleMapView");
                switchItem.Command = switchCommand;
            }
            else {
                ToolbarItems.Add(new ToolbarItem { Text = Localize("titleMapView"), Command = switchCommand });
            }
        }
    }
}

确保 lblSearchText 存在于 InitializeComponent 方法定义中。 - Ehsan Sajjad
标签控件存在于XAML中作为列表视图的一部分。它需要在XAML文件的其他地方存在吗? - Stinky Towel
请在XAML和代码后台中展示您整个页面的定义。 - Gerald Versluis
1
我认为这是因为它在模板中,所以它将针对列表中的每个项目重复,并且它们都将具有相同的名称。您想以这种方式访问它的特定原因吗?为什么不使用绑定到放入“ItemsSource”中的对象的属性呢? - Gerald Versluis
@GeraldVersluis - 我相信你是正确的!我从列表视图标签中删除了名称,将其与名称属性一起复制到相对布局节点中,然后编译通过了。请将此作为答案添加,以便我可以授予您奖励。非常感谢! - Stinky Towel
显示剩余2条评论
1个回答

2

我认为这是因为它在模板中,所以它将重复出现在列表中的每个项目中,并且它们都会有相同的名称。这是不可能的。

另外,您想以这种方式访问它是否有特定原因?为什么不使用绑定到放入ItemsSource的对象的属性呢?


我认为在这种情况下错误信息可能会更有帮助,但也许他们用它来处理各种问题。再次感谢! - Stinky Towel
技术上讲,这个错误是正确的,它不是页面的一部分,你把它放在模板里面,超出了你试图访问它的范围。但我知道你的意思 :) - Gerald Versluis
你知道那是我的第一反应,因为它不是页面的一部分,但当后面的代码允许我引用标签控件时,我认为我可以继续了。 - Stinky Towel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接