I have a Maui.net MVVM app that pings a website every xx seconds and display the ping results in a listview (for demonstrations sake I removed the ping class and instead increment a counter).
After 5 pings I want the top ping result removed so that only the last 5 ping results show in the listview.
My question is: How can I remove the top item in the ObservableCollection .
oc.Remove(), oc.RemoveAt(0) and many other variations. I Usually get the following error:
"System.ArgumentOutOfRangeException: 'This collection cannot work with indices larger than Int32.MaxValue - 1 (0x7FFFFFFF - 1). (Parameter 'index')'"
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="xPing_Maui.Views.MainPage"
BackgroundColor="LightGray" >
<ContentPage.MenuBarItems>
<MenuBarItem Text="File">
<MenuFlyoutItem Text="Save"/>
<MenuFlyoutItem Text="Exit"/>
</MenuBarItem>
<MenuBarItem Text="Settings">
<MenuFlyoutItem Text="Email Settings"/>
<MenuFlyoutItem Text="Ping Settings"/>
</MenuBarItem>
</ContentPage.MenuBarItems>
<VerticalStackLayout>
<ListView ItemsSource="{Binding ListV}" SelectionMode="Single" Background="Gray" SeparatorVisibility="None" Margin="20,20,20,20">
</ListView>
<Grid>
</Grid>
</VerticalStackLayout>
</ContentPage>
Main Page code behind
using System.Diagnostics;
using xPing_Maui.ViewModels;
namespace xPing_Maui.Views;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new VMMainPage();
}
}
ViewModel
using Microsoft.VisualBasic.FileIO;
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using xPing_Maui.Helper;
using xPing_Maui.Models;
namespace xPing_Maui.ViewModels
{
// [AddINotifyPropertyChangedInterface]
public class LVMainPage
{
public ObservableCollection<string> ListV { get; set; }
PingClass pg = new PingClass ();
[Obsolete]
public LVMainPage()
{
ListV = new ObservableCollection<string>();
int Counter = 0;
int cnt = 0;
Device.StartTimer(new TimeSpan(0, 0, 4), () =>
{
ListV.Add(Counter.ToString());
Counter++;
cnt++;
if(cnt == 5)
{
// Delete first row in the ObservableCollection
ListV.RemoveAt(0);
cnt = 0;
}
return true;
});
}
}
}