Search code examples
c#xamarinxamarin.formsxamarin.androidxamarin.ios

Xamarin Forms Refresh ListView after edit


I have a problem. I created a Database with a table based on the following class:

public class Device
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
}

In my App.xaml.cs I do the following:

static List<Device> knownDeviceList;

public App()
{
    InitializeComponent();
    MyHandler();

    MainPage = new NavigationPage(new Page1());
}

public Task MyHandler()
{
    return GetKnownDevices();
}

private async Task Get()
{
    KnownDeviceList = deviceDatabaseController.GetDevice();
}

public static List<KnownDevice> KnownDeviceList
{
    get
    {
        if (knownDeviceList == null)
        {
            knownDeviceList = new List<KnownDevice>();
        }
        return knownDeviceList;
    }
    set
    {
        knownDeviceList = value;
    }
}

After that code automatically runs, I have a filled KnownDeviceList. Now in Page1 I made a ListView with a ViewModel that shows the devices from KnownDeviceList using bindings. On that same page I made a button to add a new device, so it takes you to Page2 using a NavigationPage. But when I write the new device to the database, I use: Navigation.PopToRootAsync(); to go back, but now I want the ListView to refresh and KnownDeviceList to get the devices from the database again, so my new device is in the ListView.

How can I achieve this, because I have no idea what to do after I added it!?


Solution

  • I problem here is that you are changing the collection. But not notifying the UI about it.

    List<> will not notify the collection change on its own. Where as ObservableCollection does notify collection changes, like Add, Remove, etc. Hence the name ObservableCollection.

    Using ObservableCollection<KnownDevice> instead of List<KnownDevice> could solve this issue.