在删除播放器记录系统时,会在Xamarin Forms中引发对象引用错误

时间:2019-04-25 05:25:03

标签: xamarin xamarin.forms

在我的Xamarin Forms应用中,我试图通过单击Home屏幕中的按钮来删除播放器,但这会引发“ System.NullReferenceException:对象引用未设置为实例”此时的对象”:var playerDetails = (sender as MenuItem).CommandParameter as PlayerDetails;如何基于id删除玩家记录?我不确定如何在SQLite / Xamarin表单中创建删除查询。

PlayerDetails类:

    public class PlayerDetails : INotifyPropertyChanged
        {
            [PrimaryKey, AutoIncrement]
            public int id { get; set; }
            public string FullName { get; set; }
    ......

    }

在Home类中,SQlite连接无效:

    public Home()
            {
                InitializeComponent();
                conn = DependencyService.Get<Isqlite>().GetConnection();
                conn.CreateTable<PlayerDetails>();
                players = new ObservableCollection<PlayerDetails>();
                collectionview.ItemsSource = players;
                DisplayDetails();
            }

在单击主屏幕上的“删除播放器”按钮时进行删除操作。

     public async void DeleteButton_OnClicked(object sender, System.EventArgs e)
                {
                    bool res = await DisplayAlert("Message", "Do you want to delete a player ?", "Ok", "Cancel");

                    if(res)
                    {
                        var playerDetails = (sender as MenuItem).CommandParameter as PlayerDetails;
                        players.Remove(playerDetails);
                        conn.Delete(playerDetails);
                    }
                }

Home.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="soccerapp.Home" BackgroundColor="White" Title="Home">
        <ContentPage.Resources>
            <DataTemplate x:Key="playerTemplate">
                <ContentView>
                    <StackLayout  Margin="5,5" BackgroundColor="LightGreen">
                        <Label Text="{Binding FullName}"/>
                        <Label Text="{Binding Mobile}"/>
                        <Label Text="{Binding SoccerPosition}"/>
                        <Button Text="Remove Player"  Clicked="DeleteButton_OnClicked" WidthRequest="120" HeightRequest="50"  TextColor="White" BackgroundColor="OrangeRed"></Button>
                    </StackLayout>

                </ContentView>
            </DataTemplate>
        </ContentPage.Resources>

    <StackLayout Margin="5">
            <CollectionView x:Name="collectionview"
             ItemTemplate="{StaticResource playerTemplate}">
                <!--span here decides the number of items shows in one line. Now is 3 items one line-->
                <CollectionView.ItemsLayout>
                    <GridItemsLayout Orientation="Vertical" Span="3" />
                </CollectionView.ItemsLayout>
            </CollectionView>
    </StackLayout>
    </ContentPage>  

enter image description here

0 个答案:

没有答案