2017-03-20 17 views
0

DeviceDiscoveredで見つかった項目からリストビューを作成しようとしていますが、メインページに戻って再度検索すると重複項目が検索されます。 最も簡単な解決策は、存在する場合に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が

+0

私はあなたのコードを理解していません。 Search_Devicesが呼び出されたとき? –

+0

Search_Devicesは単にボタンプレスで呼び出されます。申し訳ありませんが明確でない場合は –

+0

deviceListはどのように定義されていますか? –

答えて

0

と呼ばれている私は、ページが焦点に戻された後に複数回表示される項目の問題を回避するために、私が働いていたアプリで同様の問題がありました、私はオーバーライドされたOnAppearing()メソッドから呼び出された別のメソッドrefresh()を作成しました。

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); 
}; 
+0

デバイスが既にdeviceListにあるかどうかを確認する2番目のソリューションを使用しました。何らかの理由で 'OnAppearing()'をオーバーライドできませんでしたが、これはうまくいきます –

関連する問題