2
respostas

System.Reflection.TargetInvocationException ao selecionar veículo

Olá. Depois de fazer a faturação do código e selecionar um veículo, logo após de instanciar o "DetalheViewModel" (assim que sai do construtor), da o seguinte erro:

Unhandled Exception:

System.Reflection.TargetInvocationException: ocorreu

 public DetalheView(Veiculo pVeiculo, Usuario pUsuario)
        {
            InitializeComponent();

            this.Veiculo = pVeiculo ?? new Veiculo();
            //this.Title = pVeiculo.Nome;
            this.Usuario = pUsuario;

            this.BindingContext = new DetalheViewModel(pVeiculo);
        }
 public DetalheViewModel(Veiculo pVeiculo)
        {
            this.Veiculo = pVeiculo ?? new Veiculo();
            this.ProximoCommand = new Command(() =>
            {
                MessagingCenter.Send<Veiculo>(pVeiculo, "Proximo");
            });
        }

Eu baixei o projeto da aula e comparei com o meu projeto os arquivos DetalheView.xaml, DetalheView.xaml.cs e o DetalheViewModel.cs mas não achei nenhuma divergência. Os dados do usuário e do veículo estão sendo passados até lá.

<?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="App1.Views.DetalheView"
             Title="{Binding Veiculo.Nome}">
    <StackLayout Padding="15">
        <TableView Intent="Settings">
            <TableRoot>
                <TableSection Title="Acessórios">
                    <SwitchCell Text="{Binding TextoFreioABS}" On="{Binding TemFreio, Mode=TwoWay}" />
                    <SwitchCell Text="{Binding TextoArCondicionado}"  On="{Binding TemAr, Mode=TwoWay}" />
                    <SwitchCell Text="{Binding TextoMp3Player}"  On="{Binding TemMp3, Mode=TwoWay}" />

                    <TextCell Text="{Binding ValorTotal, Mode=TwoWay}" />
                </TableSection>
            </TableRoot>            
        </TableView>

        <Button x:Name="buttonProximo" Text="Próximo" 
        Command="{Binding ProximoCommand}"
        VerticalOptions="End"></Button>
    </StackLayout>
</ContentPage>
        #region Propriedades

        #region Públicas

        public Veiculo Veiculo { get; set; }

        public string TextoFreioABS
        {
            get
            {
                return string.Format("Freio ABS - R$ {0}", Veiculo.FREIO_ABS_VALOR);
            }
        }
        public string TextoArCondicionado
        {
            get
            {
                return string.Format("Ar Condicionado - R$ {0}", Veiculo.AR_CONDICIONADO_VALOR);
            }
        }
        public string TextoMp3Player
        {
            get
            {
                return string.Format("MP3 Player - R$ {0}", Veiculo.MP3_PLAYER_VALOR);
            }
        }

        public bool TemFreio
        {
            get { return Veiculo.TemFreioABS; }
            set { Veiculo.TemFreioABS = value; OnPropertyChanged(); OnPropertyChanged(nameof(ValorTotal)); } 
        }
        public bool TemAr
        {
            get { return Veiculo.TemAr; }
            set { Veiculo.TemAr = value; OnPropertyChanged(); OnPropertyChanged(nameof(ValorTotal)); }
        }
        public bool TemMp3
        {
            get { return Veiculo.TemMp3Player; }
            set { Veiculo.TemMp3Player = value; OnPropertyChanged();  OnPropertyChanged(nameof(ValorTotal)); }
        }

        public string ValorTotal
        {
            get
            {
                return Veiculo.PrecoTotalFormatado;
            }
        }


        //public event PropertyChangedEventHandler PropertyChanged;
        public ICommand ProximoCommand { get; set; }

        #endregion

        #endregion

        #region Construtor

        public DetalheViewModel(Veiculo pVeiculo)
        {
            this.Veiculo = pVeiculo ?? new Veiculo();
            this.ProximoCommand = new Command(() =>
            {
                MessagingCenter.Send<Veiculo>(pVeiculo, "Proximo");
            });
        }

        #endregion

Desde já agradeço a ajuda

2 respostas

Voltou a funcionar no dia seguinte... Tinha umas páginas com xaml que estava com espaço no binding, tipo isso:

Text=" {Binding Modelo}"

Agora está quebrando depois da página de detalhes... amanhã vou olhar melhor os outros xaml...

Olá Pablo, tudo bem?

Esses problemas de reflection são realmente tensos. As vezes títulos de propriedades, espaços em branco e mais um monte de coisinhas que nem imaginamos podem ocasionar neste tipo de erro.

Mas se quiser compartilhar seu código via Dropbox, Google Drive ou Github, para que eu possa dar uma olhada, pode ser que eu te ajude a encontrar o problema.

No aguardo!

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