xamarin表单中构造函数的默认+渲染器错误和空引用错误(android)

时间:2018-03-29 19:14:13

标签: c# android xamarin constructor xamarin.forms

我在pcl项目的xaml中有一个图像列表 当我在我的samsumg galaxy s5迷你设备中测试我的应用程序时 我这样做:我进入列表的页面,然后我按下操作栏上的后退按钮...我做了很多次......然后,它发生了:

  

System.NotSupportedException:无法从本机句柄0x20e0001d(key_handle 0x42433c30)激活Xamarin.Forms.Platform.Android.Platform + DefaultRenderer类型的实例。

  

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

当我按下顶部栏上的后退按钮时正在运行的页面,出现错误 XAML (PCL):

<?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="neoFly_Montana.Views.ProdutosView"          
         xmlns:local="clr-namespace:neoFly_Montana.LayoutScripts"
         xmlns:interface="clr-namespace:neoFly_Montana.Interface"
         xmlns:effect="clr-namespace:neoFly_Montana.Effects"
         xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
         BackgroundImage="prodBackground.jpg"
         x:Name="ParentHost">

<ContentPage.Content>

        <Grid HorizontalOptions="FillAndExpand" RowSpacing="0" VerticalOptions="StartAndExpand">
        <Grid.RowDefinitions>
            <RowDefinition Height="9.5*"/>
            <RowDefinition Height="0.5*"/>
        </Grid.RowDefinitions>

        <!-- Lista de produtos -->
            <ListView Grid.Row="0" Grid.Column="0" ItemSelected="ListView_ItemSelected" CachingStrategy="RecycleElement" BackgroundColor="Transparent" x:Name="listview_produtos" Margin="10,0,10,0" SeparatorVisibility="None" HasUnevenRows="True" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

            <ListView.Header>

                <!-- Observação -->
                <StackLayout>
                <StackLayout x:Name="prod_stack_obser" IsVisible="False" Orientation="Horizontal" Spacing="0" HorizontalOptions="FillAndExpand">
                    <Label x:Name="label_observ" HorizontalTextAlignment="Start" VerticalOptions="Center" FontSize="Small" TextColor="White" Style="{StaticResource labelsfont}" Margin="20,10,0,10" />
                    <ffimageloading:CachedImage x:Name="lapis" Source="lapis.png" IsVisible="False" HorizontalOptions="EndAndExpand"/>
                </StackLayout>
                <BoxView HeightRequest="20"/>
                </StackLayout>
            </ListView.Header>

                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>

                        <Grid Margin="20,0,20,20">
                            <ffimageloading:CachedImage Source="texturaCateg.png" BackgroundColor="{Binding FundoColor, Source={x:Reference ParentHost}}" Grid.Row="0" Grid.Column="0" Aspect="Fill" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"/>

                            <StackLayout Grid.Row="0" Grid.Column="0" VerticalOptions="FillAndExpand" x:Name="produtos_stack_color" Spacing="10">

                                <StackLayout Spacing="0" Grid.Row="0" Grid.Column="0" HorizontalOptions="FillAndExpand" VerticalOptions="CenterAndExpand">

                                <StackLayout Orientation="Horizontal" Padding="10,10,10,0" VerticalOptions="Center" HorizontalOptions="FillAndExpand">
                                        <ffimageloading:CachedImage FadeAnimationForCachedImages="True" DownsampleUseDipUnits="True" DownsampleHeight="60" HeightRequest="83" WidthRequest="130" Source="{Binding imagem}" Aspect="Fill" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" >
                                            <!--<ffimageloading:CachedImage.CacheKeyFactory>
                                                <interface:CustomCacheKeyFactory/>
                                            </ffimageloading:CachedImage.CacheKeyFactory>-->
                                        </ffimageloading:CachedImage>

                                        <!--HeightRequest="83" WidthRequest="100"-->
                                        <!--DownsampleHeight="83"-->
                                        <!--<StackLayout Orientation="Horizontal" VerticalOptions="Center" HorizontalOptions="EndAndExpand">
                                                <Label Style="{StaticResource labelsfont}" Text="R$" VerticalOptions="CenterAndExpand" TextColor="{Binding TextColor, Source={x:Reference ParentHost}}" FontSize="Medium"/>
                                                <Label Style="{StaticResource labelsfont}" Text="{Binding valor}" TextColor="{Binding TextColor, Source={x:Reference ParentHost}}" FontAttributes="Bold" VerticalOptions="Start" FontSize="30"/>
                                            </StackLayout>-->

                                </StackLayout>

                                        <!--nome-->
                                    <Label Text="{Binding nome}" Margin="0,10,0,10" Style="{StaticResource labelsfont}" TextColor="{Binding TextColor, Source={x:Reference ParentHost}}" HorizontalTextAlignment="Center" FontAttributes="Bold" FontSize="Medium" HorizontalOptions="CenterAndExpand"/>

                                </StackLayout>
                                <Grid VerticalOptions="FillAndExpand">
                                    <BoxView Grid.Row="0" Grid.Column="0" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" BackgroundColor="WhiteSmoke" Opacity="0.2"/>
                                    <Label Grid.Row="0" Grid.Column="0" Margin="10,10,10,10" HorizontalTextAlignment="Center" Text="{Binding observacao}" Opacity="1" FontSize="Small" Style="{StaticResource labelsfont}" TextColor="{Binding TextColor, Source={x:Reference ParentHost}}" HorizontalOptions="Center" />
                                </Grid>
                            </StackLayout>
                        </Grid>

                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
                <ListView.Footer>

                <StackLayout>
                    <Grid x:Name="prod_rl_fundo" >
                    <Grid.Margin>
                        <OnPlatform x:TypeArguments="Thickness"
                                 iOS="20,0,20,0"
                                 Android="20,10,20,10"/>
                    </Grid.Margin>
                        <ffimageloading:CachedImage x:Name="prod_acomp_img" Source="texturaCateg.png" Grid.Row="0" Grid.Column="0" HorizontalOptions="FillAndExpand" Aspect="Fill" VerticalOptions="FillAndExpand"></ffimageloading:CachedImage>

                        <!--Acompanhamentos-->
                    <StackLayout x:Name="stack_acompanhamentos" Spacing="0" Grid.Row="0" Grid.Column="0">

                        <Grid x:Name="prod_acompanhamentos_title" HorizontalOptions="FillAndExpand">
                            <BoxView Grid.Row="0" Grid.Column="0" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" BackgroundColor="WhiteSmoke" Opacity="0.2"/>
                            <Label x:Name="produtos_acomp_title" Text="+ Dois Acompanhamentos" Grid.Row="0" Grid.Column="0" Style="{StaticResource labelsfont}" Margin="20,20,20,20" FontAttributes="Bold" VerticalOptions="CenterAndExpand" HorizontalOptions="Center" />
                        </Grid>

                    </StackLayout>
                    </Grid>

                <BoxView HeightRequest="50"></BoxView>
                </StackLayout>

            </ListView.Footer>

            </ListView>

            <!--Rodapé Grid-->
            <Grid Grid.Row="1" Grid.Column="0" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
            <ffimageloading:CachedImage Source="rodape.png" 
                       HorizontalOptions="FillAndExpand"
                       Aspect="AspectFill"
                       VerticalOptions="FillAndExpand"
                   Grid.Row="0"/>

            <!--Escrito Rodapé-->
            <StackLayout StyleId="rodapemenu" Orientation="Horizontal" 
                   Margin ="5,5,5,5" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" Grid.Row="0">
                    <Label
                   FontSize="Micro"
                   Text="Você está em:"
                   Style="{StaticResource labelsfont}"
                   VerticalOptions="CenterAndExpand"
                   TextColor="White"/>

                <StackLayout.Effects>
                    <effect:SafeAreaPaddingEffect />
                </StackLayout.Effects>

                <Label FontSize="Micro"
                   Text="loja"
                   x:Name="prod_lbl_lojaprox"
                   Style="{StaticResource labelsfont}"
                   VerticalOptions="CenterAndExpand"
                   TextColor="{StaticResource laranjacolor}"
                   LineBreakMode="TailTruncation"
                   FontAttributes="Bold" />
                </StackLayout>
            </Grid>
        </Grid>

</ContentPage.Content>

C#

using FFImageLoading;
using FFImageLoading.Forms;
using neoFly_Montana.Api;
using neoFly_Montana.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace neoFly_Montana.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ProdutosView : ContentPage
{
    List<Produtos> lstProdutos = new List<Produtos>();
    Categorias categEscolhida;
    public Color FundoColor { get { return fundoColor; } }
    public Color TextColor { get { return textColor; } }
    Color fundoColor;
    Color textColor;
    string lojaProx;
    string codLoja;

    public ProdutosView(string codLoja, Object categEscolhida, object produtos, string lojaProx)
    {

        this.codLoja = codLoja;
        this.categEscolhida = new Categorias();
        this.categEscolhida = (Categorias)categEscolhida;
        lstProdutos = (List<Produtos>)produtos;
        fundoColor = Color.FromHex(this.categEscolhida.corFundo);
        textColor = Color.FromHex(this.categEscolhida.corTexto);

        this.Title = this.categEscolhida.nome;

        //TrataImagens();

        InitializeComponent();

        if (lojaProx != null)
        {
            this.lojaProx = lojaProx;
            prod_lbl_lojaprox.Text = lojaProx;
        }

        PopulaListView();

        //if (Device.OS == TargetPlatform.iOS)
        //{
        //    this.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0);
        //}
    }

    void TrataImagens()
    {
        foreach (var item in lstProdutos)
        {
            if (item.imagem != null && item.imagem.Trim() != "")
            {

                int initIndex = item.imagem.IndexOf(',');
                 string u = item.imagem.Substring(initIndex+1);
                try
                {
                    var bytes= Convert.FromBase64String(item.imagem);
                    item.imagem = System.Text.Encoding.Unicode.GetString(bytes, 0, bytes.Length);
                  //  item.imagem = Encoding.UTF8.GetString(bytes);
                }
                catch (Exception e)
                {
                    var ss = e.Message;
                }
            }
        }
    }

    private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        var list = (ListView)sender;
        list.SelectedItem = null;
    }

    void PopulaListView()
    {

        int row = 0;
        int column = 0;

        Grid grid_acompanhamentos = new Grid
        {
           // BackgroundColor = Color.Red,
            RowSpacing = 0,
            Padding = new Thickness(0, 0, 0, 0),
            HorizontalOptions = LayoutOptions.CenterAndExpand,
            Margin = new Thickness(10, 10, 10, 10),
            ColumnSpacing = 0,

        };

        //CachedImage prod_acomp_img = new CachedImage
        //{
        //    Source = "texturaCateg.png",
        //    Aspect = Aspect.Fill,
        //    BackgroundColor = Color.FromHex(this.categEscolhida.corFundo)
        //};

        //produtos
        listview_produtos.ItemsSource = lstProdutos;

        //observação
        if (categEscolhida.observacao != null && categEscolhida.observacao.Trim() != "") {
            label_observ.Text = categEscolhida.observacao;
            prod_stack_obser.IsVisible = true;
            lapis.IsVisible = true;
        }

        //acompanhamentos
        if (categEscolhida.acompanhamentos == null || categEscolhida.acompanhamentos.Count() == 0)
        {
             stack_acompanhamentos.IsVisible = false;
        }
        else
        {
            //prod_acompanhamentos_title.BackgroundColor = fundoColor;
            prod_acomp_img.BackgroundColor = fundoColor;
            produtos_acomp_title.TextColor = textColor;

            foreach (var item in categEscolhida.acompanhamentos)
            {
                StackLayout stack = new StackLayout();
                stack.Margin =  new Thickness (0,10,0,10);
                stack.HorizontalOptions = LayoutOptions.StartAndExpand;
                //stack.BackgroundColor = Color.Orange;
                stack.Spacing = 0;

                stack.Children.Add(new Label { Text = item.nome, HorizontalTextAlignment = TextAlignment.Start, TextColor = textColor, HorizontalOptions=LayoutOptions.Start, FontAttributes = FontAttributes.Bold, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)) });

                if (item.observacao != null)
                    stack.Children.Add(new Label { Text = item.observacao, HorizontalTextAlignment = TextAlignment.Start, HorizontalOptions = LayoutOptions.Start, TextColor = textColor, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)) });
                else
                    stack.Children.Add(new Label { Text = " ", TextColor = textColor, HorizontalTextAlignment = TextAlignment.Start, HorizontalOptions = LayoutOptions.Start, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)) });


                grid_acompanhamentos.Children.Add(stack, column, row);

                if (column == 0)
                {
                    column = 1;
                }
                else
                {
                    column = 0;
                    row++;
                }
            }
            stack_acompanhamentos.Children.Add(grid_acompanhamentos);
            //produtos_rl_acompanhamentos.Children.Add(grid_acompanhamentos,
            //    Constraint.RelativeToParent((parent) =>
            //    {
            //        return (parent.Width / 2) - (grid_acompanhamentos.Width / 2);
            //    }),
            //    Constraint.RelativeToParent((parent) =>
            //    {
            //        return (parent.Height / 2) - (grid_acompanhamentos.Height / 2);
            //    })
            //);


            //produtos_rl_acompanhamentos.Children.Add(prod_acomp_img, Constraint.RelativeToParent((parent) => {
            //    return parent.X;
            //}), Constraint.RelativeToParent((parent) => {
            //    return parent.Y;
            //}), Constraint.RelativeToParent((parent) => {
            //    return parent.Width;
            //}), Constraint.RelativeToView(grid_acompanhamentos, (parent, sibling) => {
            //    var teste =   sibling.Height;
            //    return teste;
            //}));

            //UpdateConstraintsBasedOnWidth(produtos_rl_acompanhamentos, grid_acompanhamentos);
           // produtos_rl_acompanhamentos.RaiseChild(grid_acompanhamentos);
        }
    }

    public static void UpdateConstraintsBasedOnWidth(Xamarin.Forms.RelativeLayout layout, Xamarin.Forms.View view)
    {
        view.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) =>
        {
            if (e.PropertyName == "Width") { layout.ForceLayout(); }
        };

        view.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) =>
        {
            if (e.PropertyName == "Height") { layout.ForceLayout(); }
        };
    }
}
}

上一页上面的页面应该在发生错误时返回 XAML (PCL)

<?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="neoFly_Montana.Views.CategoriasView"
         xmlns:effect="clr-namespace:neoFly_Montana.Effects"
         xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
         Title="Cardápio">
<ContentPage.Content>

    <Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

        <ffimageloading:CachedImage Source="familiaBackground.jpg" Grid.Row="0" Grid.Column="0" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Aspect="Fill"/>

        <!--Categ grid-->
        <Grid Grid.Row="0" Grid.Column="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="9.5*"/>
                <RowDefinition Height="0.5*"/>
            </Grid.RowDefinitions>

            <Grid x:Name="gridtextura" RowSpacing="20" BindingContext="{Binding nome}" Padding="10, 10, 10, 10" Margin="10,10,10,10"/>

            <!--Rodapé Grid-->
            <Grid Grid.Row="1" Grid.Column="0" VerticalOptions="FillAndExpand">

                <Image Source="rodape.png" 
                   Aspect="Fill"
                   Grid.Row="0"
               VerticalOptions="FillAndExpand"/>

                <!--Escrito Rodapé-->
                <StackLayout StyleId="rodapemenu" Orientation="Horizontal" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" Grid.Row="0" Grid.Column="0">
                    <StackLayout.Effects>
                        <effect:SafeAreaPaddingEffect />
                    </StackLayout.Effects>

                    <Label
                   FontSize="Micro"
                   Text="Você está em:"
                   Style="{StaticResource labelsfont}"
                   VerticalOptions="CenterAndExpand"
                   TextColor="White"/>

                    <Label FontSize="Micro"
                   Text="loja"
                   x:Name="categorias_lbl_ljproxima"
                   Style="{StaticResource labelsfont}"
                   VerticalOptions="CenterAndExpand"
                   TextColor="{StaticResource laranjacolor}"
                   LineBreakMode="TailTruncation"
                   FontAttributes="Bold" />

                </StackLayout>
            </Grid>

        </Grid>
    </Grid>
</ContentPage.Content>

代码背后

using FFImageLoading.Forms;
using neoFly_Montana.Api;
using neoFly_Montana.Model;
using neoFly_Montana.PopUp;
using Rg.Plugins.Popup.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace neoFly_Montana.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CategoriasView : ContentPage
{
    ActivityIndicator indicator;

    string codigoLoja;
    List<Categorias> lstCategorias;

    List<Produtos> lstProdutos = new List<Produtos>();
    List<Acompanhamento> lstAcompanhamentos;

    Categorias categoriaEscolhida;

    string observacao;

    string codCategoria;

    string lojaProx;

    LoadingPopUp loading;

    public CategoriasView(string codigoLoja, string lojaProx, object lstCategorias)
    {
        this.codigoLoja = codigoLoja;
        this.lojaProx = lojaProx;
        //this.codigoLoja = "162";
        this.lstCategorias = (List<Categorias>)lstCategorias;
        InitializeComponent();
        categorias_lbl_ljproxima.Text = lojaProx;
        CriaTela();
    }

    void CriaLoading()
    {
        LoadingPopUp loading = new LoadingPopUp("Carregando...", Color.Brown);
        PopupNavigation.PushAsync(loading, false);
    }

    private void CriaTela()
    {
        int row = 0;
        int column = 0;

        gridtextura.RowSpacing = 5;
        gridtextura.ColumnSpacing = 15;

        lstCategorias = lstCategorias.OrderBy(o => o.nome).ToList();

        foreach (var item in lstCategorias)
        {
            Grid GridContent = new Grid
            {
                RowSpacing = 0,
                Margin = new Thickness(0, 5, 0, 0),
                VerticalOptions = LayoutOptions.FillAndExpand,
                RowDefinitions =
            {
                new RowDefinition { Height = new GridLength(8, GridUnitType.Star) },
                new RowDefinition { Height = new GridLength(2, GridUnitType.Star) }
            }
            };

            var textura = new CachedImage();
            textura.Source = "texturaCateg";
            textura.HorizontalOptions = LayoutOptions.FillAndExpand;
            textura.VerticalOptions = LayoutOptions.FillAndExpand;
            textura.Aspect = Aspect.Fill;

            GridContent.BindingContext = item;

            Grid boxColorView = new Grid
            {
                RowSpacing = 0,
                //InputTransparent = true,
                VerticalOptions = LayoutOptions.FillAndExpand,
                RowDefinitions =
            {
                new RowDefinition { Height = new GridLength(2, GridUnitType.Star) },
                new RowDefinition { Height = new GridLength(8, GridUnitType.Star) }
            }
            };

            boxColorView.Children.Add(new StackLayout { BackgroundColor = Color.FromHex(item.corFundo), VerticalOptions = LayoutOptions.FillAndExpand }, 0, 1);
            boxColorView.Children.Add(textura, 0, 1);

            //  boxColorView.Children.Add(new BoxView { VerticalOptions = LayoutOptions.FillAndExpand }, 0, 0);
            gridtextura.Children.Add(boxColorView, column, row);
            gridtextura.Children.Add(GridContent, column, row);

            //Qual categoria foi escolhida?
            var CliqueCategoria = new TapGestureRecognizer();
            CliqueCategoria.NumberOfTapsRequired = 1;
            CliqueCategoria.Tapped += (s, e) =>
            {
                CriaLoading();
                var stacklayout = s as Grid;
                categoriaEscolhida = (Categorias)stacklayout.BindingContext;
                ChamaProdutos();
            };

            GridContent.GestureRecognizers.Add(CliqueCategoria);

            if (item.imagem != null && item.imagem != "")
            {
                int initIndex = item.imagem.IndexOf(',');
                string image = "";

                image = item.imagem.Substring(initIndex + 1);

                try
                {
                    GridContent.Children.Add(new CachedImage { Source = ImageSource.FromStream(() => new MemoryStream(Convert.FromBase64String(image))), VerticalOptions = LayoutOptions.FillAndExpand, DownsampleHeight = 60 }, 0, 0);
                }
                catch (Exception e)
                {
                    GridContent.Children.Add(new CachedImage { Source = "error.png", VerticalOptions = LayoutOptions.FillAndExpand, DownsampleHeight = 50, HorizontalOptions = LayoutOptions.Fill, HeightRequest = 50, WidthRequest = 50 }, 0, 0);

                }
            }

            GridContent.Children.Add(new Label { Text = item.nome, TextColor = Color.FromHex(item.corTexto), FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), FontAttributes = FontAttributes.Bold, HorizontalTextAlignment = TextAlignment.Center, VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.CenterAndExpand, LineBreakMode = LineBreakMode.TailTruncation }, 0, 1);

            if (column == 0)
            {
                column = 1;
            }
            else
            {
                column = 0;
                row++;
            }

        }

    }

    async Task ChamaProdutos()
    {
        await CallingProdutosAsync();
        await CallingAcompanhamentosAsync();
        await Navigation.PushAsync(new Views.ProdutosView(codigoLoja, categoriaEscolhida, lstProdutos, lojaProx), true);

        PopupNavigation.PopAsync();

        if (lstProdutos == null)
            DisplayAlert("Ops", "Verifique sua conexão com a internet e tente novamente.", "Ok");

    }

    //carregamento de dados para a tela de produtos
    async Task CallingProdutosAsync()
    {
        lstProdutos = await Webservice.GetProdutosAsync(codigoLoja, categoriaEscolhida.idCategoria);
    }

    //este pode estar zerado
    async Task CallingAcompanhamentosAsync()
    {
        categoriaEscolhida.acompanhamentos = new List<Acompanhamento>();
        categoriaEscolhida.acompanhamentos = await Webservice.GetAcompanhamentoAsync(codigoLoja, categoriaEscolhida.idCategoria);
    }
}
}

我问我是否只是调试模式错误。我正在测试它... ---更新---- 在发布模式中它正在发生:(

0 个答案:

没有答案