清除重复项目的列表视图

时间:2017-03-20 12:41:51

标签: listview xamarin.android xamarin.forms

我尝试使用DeviceDiscovered找到的项目构建列表视图,但是当我导航回主页面时,它会工作,并再次搜索listview获取重复项目。 我认为最简单的解决方案是清除整个deviceList(如果存在)。虽然它不起作用。

我还尝试设置listview.ItemsSource = null,然后再次将其设置为deviceList。但我仍然得到重复的项目。

public App()
    {

        // The root page of your application
        var button = new Button
        {
            Text = "Search devices",
        };
        button.Clicked += Search_Devices;

        var content = new ContentPage
        {
            Title = "BluetoothApp",
            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.Fill,
                Children = { button }
            }
        };

        MainPage = new NavigationPage(content);
    }

private async void Search_Devices(object sender, EventArgs e)
    {
        //Get bluetooth adapter
        var ble = CrossBluetoothLE.Current;
        adapter = CrossBluetoothLE.Current.Adapter;

        //Clear devicelist when it exists
        if (deviceList != null)
        {
            deviceList.Clear();
        }

        //Create devicelist
        deviceList = new List<Plugin.BLE.Abstractions.Contracts.IDevice>();
        adapter.DeviceDiscovered += async (s, a) =>
        {
            deviceList.Add(a.Device);
        };
        await adapter.StartScanningForDevicesAsync();

        //Create listview from devices
        ListView listview = new ListView();
        listview.ItemsSource = deviceList;
        listview.ItemTapped += Listview_ItemTapped;

        ContentPage devices_page = new ContentPage
        {
            Title = "Devices",
            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.Fill,
                Children = { listview }
            }
        };
        await MainPage.Navigation.PushAsync(devices_page);
    }

编辑:添加了调用Search_Button的地方

2 个答案:

答案 0 :(得分:1)

我建议查看https://github.com/jamesmontemagno/mvvm-helpers
它有ObservableRangeCollection,其中包含ReplaceReplaceRange

来源:https://github.com/jamesmontemagno/mvvm-helpers/blob/master/MvvmHelpers/ObservableRangeCollection.cs

答案 1 :(得分:0)

我在我正在处理的应用中遇到了类似的问题,为了解决在页面重新聚焦后多次出现的项目问题,我创建了一个名为refresh()的单独方法,我从重写的OnAppearing()方法。

在刷新方法本身中,将List声明为新列表,每次调用它时,总是以干净的,新的和空的List开头。

async void refresh()
{
    deviceList = new List<Plugin.BLE.Abstractions.Contracts.IDevice>();
    //populate the list
    listview.ItemSource = deviceList;
}

如果这对您不起作用,您始终可以创建一个循环来检查项目是否已经在列表中,并且只有在已经存在的项目时才添加它。

adapter.DeviceDiscovered += async (s, a) =>
{
    if(!deviceList.Contains(a.Device)
        deviceList.Add(a.Device);
};