如何在Xamarin中从ListView中删除所选项目

3

我正在构建一个Xamarin跨平台应用程序!

该应用程序包含2个页面:HomePage(主页)DetailGetData(获取详细数据)

HomePage: 该页面包含一个ListView,其中显示来自WebApi的数据列表。每当我单击每个单元格时,它都会转到DetailGetData页面,显示该数据的详细信息。

问题: 现在的问题是,我想从DetailGetData页面删除所选项。放置了DeleteButton(删除按钮),当我按下该按钮时,列表中的详细信息和所选项都将被删除。 如何实现?

DetailGetData屏幕截图:https://istack.dev59.com/TXg4G.webp

HomePage屏幕截图:https://istack.dev59.com/g1Hn1.webp

代码:

DetailGetData 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="Last_MSPL.Views.DetailGetData">

    <StackLayout HorizontalOptions="Center" VerticalOptions="Center">

        <Label Text="{Binding employee_name}" x:Name="empname" FontSize="Medium" FontAttributes="Bold" />
        <Label Text="{Binding employee_age}" x:Name="age" FontSize="Medium" FontAttributes="Bold" />
        <Label Text="{Binding employee_salary}" x:Name="salary" FontSize="Medium" FontAttributes="Bold" />

        <Button x:Name="DeleteItem" Text="Delete" Clicked="DeleteItem_Clicked"  />
    </StackLayout>

</ContentPage>

主页 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="Last_MSPL.HomePage">


    <AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        <ListView x:Name="Demolist" ItemSelected="OnItemSelected" BackgroundColor="White">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell Height="100">
                        <ViewCell.ContextActions>
                            <MenuItem x:Name="OnMore" Clicked="OnMore_Clicked" CommandParameter="{Binding .}"
                                 Text="More" />
                            <MenuItem x:Name="OnDelete" Clicked="OnDelete_Clicked" CommandParameter="{Binding .}"
                                 Text="Delete" IsDestructive="True" />
                        </ViewCell.ContextActions>
                        <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Padding="30,0">

                            <Label Text="{Binding employee_name}" FontAttributes="bold" FontSize="Small" TextColor="Black" x:Name="en"/>
                            <Label Text="{Binding employee_age}" FontSize="Micro" TextColor="Black" FontAttributes="Italic"/>
                            <Label Text="{Binding id}" IsVisible="False" />


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

        <ImageButton Source="fedit.png" 
            BackgroundColor="Transparent"
            AbsoluteLayout.LayoutFlags="PositionProportional"  
            AbsoluteLayout.LayoutBounds=".95,.95,55,55" 
            Clicked="ImageButton_Clicked">
        </ImageButton>

    </AbsoluteLayout>
</ContentPage>

HomePage.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Last_MSPL.MenuItems;
using Last_MSPL.Views;
using System.Collections;

namespace Last_MSPL
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class HomePage : ContentPage
    {
        public IEnumerable ObjOrderList { get; private set; }


        public HomePage()
        {
            ((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.Black;
            InitializeComponent();
            Get();
        }



        public async void Get()
        {
            HttpClient client = new HttpClient();
            try
            {
                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var totalCount = ObjOrderList.Count;
                Demolist.ItemsSource = ObjOrderList.GetRange(0, 40);
            }
            catch (Exception ex)
            {
                throw;
            }
        }


        public async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            HttpClient client = new HttpClient();
            if (Demolist.SelectedItem != null)
            {

                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var abc = (GetData)e.SelectedItem;

                GetData data = new GetData();
                data = ObjOrderList.ToList().Where(x => x.id == abc.id).FirstOrDefault();

                var detailPage = new DetailGetData(data);
                detailPage.BindingContext = e.SelectedItem as GetData;
                Demolist.SelectedItem = null;
                await Navigation.PushModalAsync(detailPage);

            }
        }

DetailGetData.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Last_MSPL.MenuItems;

namespace Last_MSPL.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class DetailGetData : ContentPage
    {
        public DetailGetData(GetData _data)
        {
            InitializeComponent();
            BindingList(_data);

        }



        public void BindingList(GetData data)
        {
            empname.Text = data.employee_name;
            age.Text = data.employee_age;
            salary.Text = data.employee_salary;
        }


        public async void DeleteItem_Clicked(object sender, EventArgs e)
        {





            await Navigation.PopModalAsync();
        }
    }
}

@WasifMahmoodMustafa已添加。请现在检查一下,如果您能帮助我解决这个问题! - Hashir Malik
不,你的详细页面应该引发一个“已删除”事件,而你的主页将订阅该事件。 - Jason
@Jason,这将如何完成? - Hashir Malik
你需要更具体地说明你不理解的是什么。C#中的自定义事件有很好的文档,应该很容易查找到。 - Jason
@Jason 简单来说,我只是想通过按钮事件从列表视图中删除所选项目! - Hashir Malik
显示剩余3条评论
2个回答

3

通过添加静态数据源类,您可以实现删除项目的功能。并设置Demolist.ItemsSource = DataSource.collection; 在DetailGetData页面中单击delete按钮时,通过删除该项来修改Demolist.ItemsSource。 因此代码如下:

DataSource.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace App10
{
    public static class DataSource
    {
        public static ObservableCollection<GetData> collection;

        static DataSource()
        {
        }
        public static void persist(List<GetData> collection)
        {
            //do something here
        }

        public static void initializeData(List<GetData> listdata)
        {
            collection = new ObservableCollection<GetData>(listdata);
        }
    }
}

MainPage.xaml.cs

[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MainPage : ContentPage
    {
        List<GetData> dataList;
        public MainPage()
        {
            //((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.Black;
            InitializeComponent();
            Get();
            //RefreshList();
        }
        public async void Get()
        {
            HttpClient client = new HttpClient();
            try
            {
                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var totalCount = ObjOrderList.Count;

                dataList = ObjOrderList.GetRange(0, 40);
                DataSource.initializeData(dataList);
                Demolist.ItemsSource = DataSource.collection;

            }
            catch (Exception ex)
            {
                throw;
            }
        }


        public async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            HttpClient client = new HttpClient();
            if (Demolist.SelectedItem != null)
            {

                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var abc = (GetData)e.SelectedItem;

                GetData data = new GetData();
                data = ObjOrderList.ToList().Where(x => x.id == abc.id).FirstOrDefault();

                var detailPage = new DetailGetData(data);
                detailPage.BindingContext = e.SelectedItem as GetData;
                Demolist.SelectedItem = null;
                await Navigation.PushModalAsync(detailPage);

            }
        }
}

DetailGetData.xaml.cs

   [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class DetailGetData : ContentPage
    {
        public GetData thisData;

        public DetailGetData(GetData _data)
        {
            InitializeComponent();
            BindingList(_data);
            thisData = _data;

        }


        public void BindingList(GetData data)
        {
            empname.Text = data.employee_name;
            age.Text = data.employee_age;
            salary.Text = data.employee_salary;
        }


        public async void DeleteItem_Clicked(object sender, EventArgs e)
        {

            GetData toberemoveditem = (from item in DataSource.collection
                                       where item.id == thisData.id
                             select item)
                            .FirstOrDefault<GetData>();
            DataSource.collection.Remove(toberemoveditem);


            await Navigation.PopModalAsync();
        }
    }

还有一件事,如果你能帮忙的话。这只适用于运行时,如果我想从我的Web API中删除,我应该怎么做? - Hashir Malik
您可以通过在URL“http://dummy.restapiexample.com/api/v1/employees”上删除数据来从WebAPI中删除。请参考https://learn.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/consuming/rest。 - AbbyWang - MSFT

2
在某个类中初始化您的列表并使其成为静态的,在主页中使用它。然后在详细页面中的删除事件中,只需编写此代码即可从列表中删除该项。"最初的回答"
var remove = list.Where(x => x.employee_name == empname.Text).Single();
list.Remove(remove);

根据您的模型类更改代码。希望能对您有所帮助。

注:Original Answer翻译成"最初的回答"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接