2
respostas

Adicionar objetos a uma List de uma classe

Eu estou tentando fazer um app de uma lanchonete, criei uma classe prato e uma classe Ingredientes que depois irei atribuir alguns do ingredientes criados a cada prato.

Ele Executa certo até eu adicionar a linha

 XBurger.IngredienteDoPrato.Add(Bife);

depois disso o app executa mais trava, tanto que quando eu fecho o app no aparelho o visual ainda continua compilando o mesmo, o certo seria parar a compilação.

namespace AppGourmet.Models
{
    public class ListagemPratos
    {
        public List<Pratos> Pratos { get; private set; }

        public List<Ingredientes> Ingredientes { get; private set; }

        public List<Ingredientes> Adicionais { get; private set; }

        public ListagemPratos()
        {
            this.Ingredientes = new List<Ingredientes>()

            Ingredientes Bife = new Ingredientes();
            Bife.NomeIngrediente = "Bife";
            Ingredientes.Add(Bife);


            this.Pratos = new List<Pratos>()

            Pratos XBurger = new Pratos();
            XBurger.Nome = "X-Burger";
            XBurger.Preco = 10;
            XBurger.ImageURL = "https://cdn5.bobsfa.com.br/assets/cardapio/produtos/picanha-barbecue-100g.g.png";
            XBurger.IngredienteDoPrato.Add(Bife);
            Pratos.Add(XBurger);
        }
    }
}
namespace AppGourmet.Models
{
    public class Ingredientes
    {
        public string NomeIngrediente { get; set; }
        public decimal PrecoIngrediente { get; set; }
        public string PrecoFormatadoIngrediente
        {
            get
            {
                return string.Format("R$ {0}", PrecoIngrediente);
            }
        }
    }
}
namespace AppGourmet.Models
{
    public class Pratos
    {
        public string Nome { get; set; }
        public decimal Preco { get; set; }
        public string PrecoFormatado
        {
            get
            {
                return string.Format("R$ {0}", Preco);
            }
        }
        public string ImageURL { get; set; }

        public List<Ingredientes> IngredienteDoPrato { get; set; }
    }
}
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:AppGourmet"
             xmlns:vm="clr-namespace:AppGourmet.ViewModels"
             Title="Lanches"
             x:Class="AppGourmet.Views.ListagemView">

    <ContentPage.BindingContext>
        <vm:ListagemViewModel></vm:ListagemViewModel>
    </ContentPage.BindingContext>

    <ListView x:Name="ListViewPratos"
              BackgroundColor="White"
              ItemsSource="{Binding Pratos}"
              SelectedItem="{Binding PratoSelecionado}"
              HasUnevenRows="True">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <StackLayout Orientation="Vertical" BackgroundColor="White" Margin="10">
                            <StackLayout Orientation="Horizontal" BackgroundColor="White">
                                <Image Source="{Binding ImageURL}" HeightRequest="55" WidthRequest="55"></Image>
                                <Label Text="{Binding Nome}" FontSize="20" VerticalOptions="Center" TextColor="Blue"></Label>
                                <Label Text="  " HorizontalOptions="StartAndExpand" VerticalOptions="Center"></Label>
                                <Label Text="{Binding PrecoFormatado}" FontAttributes="Bold" VerticalOptions="Center" TextColor="Black"></Label>
                            </StackLayout>
                            <Label Text="ingrediente" TextColor="Gray"></Label>
                        </StackLayout>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

</ContentPage>
2 respostas

Olá, Alexander

O problema é que você não está inicializando a lista de ingredientes:

public List<Ingredientes> IngredienteDoPrato { get; set; }

Note que IngredienteDoPrato nunca é inicializada. Você precisa criar um construtor na classe Prato e inicializar a lista de ingredientes:

public Pratos
    {
        this.IngredienteDoPrato = new List<Ingredientes>();
    }

eu não consegui implementar essa mudança, eu tinha mudado um pouco o código, mais a parte da listagem

no caso, eu queria adicionar os items da classe ingrediente na classe prato, para eu poder imprimir esses ingredientes em uma label da Listagem

ListagemPratos.cs

namespace AppGourmet.Models
{
    public class ListagemPratos
    {
        public List<Pratos> Pratos { get; private set; }

        public List<Ingredientes> Ingredientes { get; set; }



        //public List<Ingredientes> Adicionais { get; set; }

        //--------------------------------------------------------------------------

        public ListagemPratos()
        {
            this.Ingredientes = new List<Ingredientes>()
            { 
                new Ingredientes {NomeIngrediente = "Pão"},
                new Ingredientes {NomeIngrediente = "Bife"},
                new Ingredientes {NomeIngrediente = "Presunte"},
                new Ingredientes {NomeIngrediente = "Mussarela"},
                new Ingredientes {NomeIngrediente = "Calabresa"},
                new Ingredientes {NomeIngrediente = "Ovo"},
                new Ingredientes {NomeIngrediente = "Salada(Alface e Tomate)"},
                new Ingredientes {NomeIngrediente = "Bacon"},
                new Ingredientes {NomeIngrediente = "Cheddar"},

            };

            this.Pratos = new List<Pratos>()
            { 
                new Pratos { Nome = "X-Burger", Preco = 10, ImageURL="https://cdn5.bobsfa.com.br/assets/cardapio/produtos/picanha-barbecue-100g.g.png"},
                new Pratos { Nome = "X-Bacon", Preco = 13, ImageURL="https://cdn5.bobsfa.com.br/assets/cardapio/produtos/picanha-barbecue-100g.g.png" },
                new Pratos { Nome = "X-EggBacon", Preco = 14, ImageURL="https://cdn5.bobsfa.com.br/assets/cardapio/produtos/picanha-barbecue-100g.g.png" },
                new Pratos { Nome = "X-Tudo", Preco = 16, ImageURL="https://cdn5.bobsfa.com.br/assets/cardapio/produtos/picanha-barbecue-100g.g.png" },
                new Pratos { Nome = "X-Cheddar", Preco = 19, ImageURL="https://cdn5.bobsfa.com.br/assets/cardapio/produtos/picanha-barbecue-100g.g.png" }, 
            };



        }
    }
}

Pratos.cs

namespace AppGourmet.Models
{
    public class Pratos
    {
        public string Nome { get; set; }
        public decimal Preco { get; set; }
        public string PrecoFormatado
        {
            get
            {
                return string.Format("R$ {0}", Preco);
            }
        }
        public string ImageURL { get; set; }

        //----------------------------------------------------------
        public List<Ingredientes> IngredientePrato { get; set; }
        //----------------------------------------------------------

    }
}

Ingrdediente.cs

namespace AppGourmet.Models
{
    public class Ingredientes
    {

        public string NomeIngrediente { get; set; }
        public decimal PrecoIngrediente { get; set; }
        public string PrecoFormatadoIngrediente
        {
            get
            {
                return string.Format("R$ {0}", PrecoIngrediente);
            }
        }

    }
}

ListagemView.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"
             xmlns:local="clr-namespace:AppGourmet"
             xmlns:vm="clr-namespace:AppGourmet.ViewModels"
             Title="Lanches"
             x:Class="AppGourmet.Views.ListagemView">

    <ContentPage.BindingContext>
        <vm:ListagemViewModel></vm:ListagemViewModel>
    </ContentPage.BindingContext>

    <ListView x:Name="ListViewPratos"
              BackgroundColor="White"
              ItemsSource="{Binding Pratos}"
              SelectedItem="{Binding PratoSelecionado}"
              HasUnevenRows="True">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <StackLayout Orientation="Vertical" BackgroundColor="White" Margin="10">
                            <StackLayout Orientation="Horizontal" BackgroundColor="White">
                                <Image Source="{Binding ImageURL}" HeightRequest="55" WidthRequest="55"></Image>
                                <Label Text="{Binding Nome}" FontSize="20" VerticalOptions="Center" TextColor="Blue"></Label>
                                <Label Text="  " HorizontalOptions="StartAndExpand" VerticalOptions="Center"></Label>
                                <Label Text="{Binding PrecoFormatado}" FontAttributes="Bold" VerticalOptions="Center" TextColor="Black"></Label>
                            </StackLayout>
                            <Label Text="{Binding IngredientePrato, StringFormat='{0},'}"></Label>
                        </StackLayout>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

</ContentPage>

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software