如何更改所选视图的属性

时间:2018-03-21 03:02:20

标签: c# xaml xamarin.forms

我需要在Label或StackLayout中进行一些更改。我想点击项目后,例如更改textcolor或backgroundcolor。点击Bought in Context Menu后,它给了我:Unhandled Exception:

System.NullReferenceException:未将对象引用设置为对象的实例。

这是XAML代码:

<ContentPage.Content>
    <StackLayout>
        <ListView x:Name="productsList" ItemsSource="{Binding}" ItemSelected="OnItemSelected">
            <ListView.ItemTemplate>
                <DataTemplate >
                    <ViewCell>
                        <ViewCell.View>
                            <StackLayout Orientation="Horizontal">

                                <Label  x:Name="{Binding ProdListId}" Text="{Binding Name}" FontSize="Medium"/>

                            </StackLayout>
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Button Text="ADD" Clicked="AddProducts"/>
    </StackLayout>
</ContentPage.Content>

C#:

    protected override void OnAppearing()
    {
        productsList.ItemsSource = App.Database.GetProductListItems(ListID);
        base.OnAppearing();
    }


    private async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        var action = await DisplayActionSheet("Choose action", "Cancel", null, "Delete", "Bought");
        switch (action)
        {
            case "Delete":
                Product selectedProduct = (Product)e.SelectedItem;
                App.Database.DeleteProductOfListItem(selectedProduct.ProdListId);
                // this.Navigation.PopAsync();
                OnAppearing();
                break;

            case "Bought":
                Product selectedProduct2 = (Product)e.SelectedItem;
                App.Database.UpdateProductActive(true, selectedProduct2.ProdListId);                                                 
             var lbl = this.FindByName<Label>(selectedProduct2.ProdListId.ToString());
                lbl.TextColor = Color.Green;
                break;

        }
    }

0 个答案:

没有答案