名称“ LikeShop”在当前上下文中不存在

时间:2019-05-09 07:41:40

标签: c# xamarin.forms

在我的代码中有此错误。当用户点击图片时,我想更改图片“ LikeShop”。图片的来源应从“ EmpytLove.png”变为“ Love_tab.png”

这是我的C#代码:

    public ShopPage()
    {
        InitializeComponent();
        Xamarin.Forms.NavigationPage.SetHasNavigationBar(this, false);
        On<Xamarin.Forms.PlatformConfiguration.iOS>().SetUseSafeArea(true);
        BindingContext = new MyListViewModel();
    }
    void LikeShop_Tapped(object sender, System.EventArgs e)
    {
        LikeShop.Source = "Love_tab.png";

    }
}

这是我的xml代码:

<ListView ItemsSource="{Binding MyListCollector}" IsPullToRefreshEnabled="true" x:Name="EmployeeListView" HasUnevenRows="true" ItemTapped="Handle_ItemTapped" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Image Source="Profile.png" HeightRequest="50" WidthRequest="50"/>
                            <StackLayout HorizontalOptions="StartAndExpand">
                                <Label Text="{Binding nome}" FontAttributes="Bold"/>
                            </StackLayout>
                            <Image x:Name="LikeShop" Source="EmptyLove.png">
                                  <Image.GestureRecognizers>
                                  <TapGestureRecognizer Tapped="LikeShop_Tapped" NumberOfTapsRequired="1" />
                                </Image.GestureRecognizers>
                            </Image>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView> 

1 个答案:

答案 0 :(得分:1)

原因: 图片在列表视图中。因此,无法通过调用其name来使用它。

解决方案:

事件 void LikeShop_Tapped(object sender,System.EventArgs e)有两个参数。这里的发件人是您点击的图像,因此可以获取它。

void LikeShop_Tapped(object sender, System.EventArgs e)
{
    var LikeShop= sender as Image;
    if(LikeShop.Source.ToString()=="File: Love_tab.png")
    {
       LikeShop.Source = "EmptyLove.png";
    }

    else
    {
       LikeShop.Source = "Love_tab.png";
    }
}

您可以从xaml中删除x:Name =“ xxx”。在列表视图中使用名称是不明智的。