添加MasterDetailPage后,Xamarin.forms应用程序中的System.InvalidCastException

时间:2017-06-28 14:16:41

标签: c# xamarin visual-studio-2015 xamarin.forms

我创建了一个Xamarin表单应用程序,它将用户输入的数据存储在sqlite数据库中,然后显示在列表中。直到这一点,一切都很好。正确地存储和检索数据。然后我按照教程添加MasterDetailPage。应用程序构建成功但它提供 System.InvalidCastException:指定的强制转换在mgmain JNI_OnLoad 中无效。 MainActivitiy.cs中的异常 LoadApplication(new App()); 方法。经过深入的搜索,我无法弄清楚问题出在哪里。

这是App.cs,其中MainMenuPage是MasterDetailPage

namespace MyListXamarinForms
{

  public class App : Application
    {

        public App()
        {

            MainPage = new MainMenuPage();
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}

MainMenuPage.xaml(包含MasterPage和详细信息的母版页 - 如下所示)`

<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  x:Class="MyListXamarinForms.MainMenuPage"
                  xmlns:local="clr-namespace:MyListXamarinForms">

  <MasterDetailPage.Master>
    <local:MasterPage x:Name="master"/>
  </MasterDetailPage.Master>

  <MasterDetailPage.Detail>
    <NavigationPage>
      <x:Arguments>
        <local:DetailPage/>
      </x:Arguments>
    </NavigationPage>
  </MasterDetailPage.Detail>
</MasterDetailPage>

MainMenuPage.xaml.cs`

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace MyListXamarinForms
{
    public partial class MainMenuPage : MasterDetailPage
    {
        public MainMenuPage()
        {
            InitializeComponent();

            master.ListViews.ItemSelected += OnItemSelected;
        }

        private void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var item = e.SelectedItem as MasterPageItem;
            if(item!=null)
            {
                Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType));
                master.ListViews.SelectedItem = null;
                IsPresented = false;
            }
        }
    }
}`

MasterPage.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"
             x:Class="MyListXamarinForms.MasterPage"
             Icon=""
             Title="Menu"
             Padding="0,50,0,0">
  <ContentPage.Content >
    <StackLayout VerticalOptions="FillAndExpand">
      <ListView x:Name="MenuList" VerticalOptions="FillAndExpand" SeparatorVisibility="None">
        <ListView.ItemTemplate>
          <DataTemplate>
            <Label x:Name="ItemNameLabel" Text="{Binding Title}"/>
          </DataTemplate>
        </ListView.ItemTemplate>            
      </ListView>          
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

MasterPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;

namespace MyListXamarinForms
{
    public partial class MasterPage : ContentPage
    {
        public ListView ListViews { get { return MenuList; } }
        public MasterPage()
        {
            InitializeComponent();

            var masterPageItem = new List<MasterPageItem>();

            //AddItem and HomePage are two ContentPages with content
            masterPageItem.Add(new MasterPageItem {
                Title = "Add Item",
                TargetType = typeof(AddItem)
            });
            masterPageItem.Add(new MasterPageItem
            {
                Title = "View Item List",
                TargetType = typeof(HomePage)
            });

            MenuList.ItemsSource = masterPageItem;
        }
    }
}

MasterPageItem.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyListXamarinForms
{
    public class MasterPageItem
    {
        public string Title { get; set; }
        public Type TargetType { get; set; }
    }
}

MyListXamarinForms.Droid MainActivity.cs

using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace MyListXamarinForms.Droid
{
    [Activity(Label = "MyListXamarinForms", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new App());  //Exception thrown here
        }
    }
}

`

3 个答案:

答案 0 :(得分:5)

在您的情况下,您不需要ImageCell,因为您只是显示标签,但ListView的DataTemplate必须是Cell,因此您可以这样做:

<DataTemplate> 
    <TextCell x:Name="ItemNameLabel" Text="{Binding Title}"/> 
</DataTemplate>

- TextCell很简单,带有标签的单元格。

或者这个:

 <DataTemplate> 
     <ViewCell>
        <Label x:Name="ItemNameLabel" Text="{Binding Title}"/>
    </ViewCell>
</DataTemplate>

- 请注意这只是将标签包装在ViewCell

答案 1 :(得分:2)

我遇到了完全相同的问题。我正在尝试自定义我的母版页,问题是当它期望接收“ImageCell”时,你只在DataTemplate中放置一个“标签”,因此“无效的强制转换”异常。

<?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="MyListXamarinForms.MasterPage"
         Icon=""
         Title="Menu"
         Padding="0,50,0,0">
<ContentPage.Content >
    <StackLayout VerticalOptions="FillAndExpand">
      <ListView x:Name="MenuList" VerticalOptions="FillAndExpand" SeparatorVisibility="None">
        <ListView.ItemTemplate>
          <DataTemplate>
            <ImageCell Text="{Binding Title}" ImageSource="{Binding IconSource}"/>
          </DataTemplate>
        </ListView.ItemTemplate>            
      </ListView>          
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

将DataTemplate替换为上面的代码,它应该可以工作。虽然如果有人知道如何自定义DataTemplate以放置除ImageCell以外的东西,我很乐意知道!

干杯:)

答案 2 :(得分:0)

就我而言,我使用CollectionView而不是ListView。它具有一个自定义的DataTemplate和一个EmptyView,可以帮助很多。 简介:https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/collectionview/introduction

<CollectionView x:Name="MenuList">
    <CollectionView.ItemTemplate>
      <DataTemplate>
        <...Your cell here...>
      </DataTemplate>
    </CollectionView.ItemTemplate>            
  </CollectionView>    

我摆脱了那个例外,此后没有任何机会。