Home > Back-end >  ObservableCollection not updating DataGrid when item is updated
ObservableCollection not updating DataGrid when item is updated

Time:10-11

I'm trying to deserialize a json file and then use the resulting observable collection to source a Datagrid control. Until here everything is ok.

When I try to update the collection, Datagrid is not updated until I scroll it. I don't know why, I understand with an observable collection Datagrid should be updated automatically.

Here is my code:

MainWindow.xaml.cs:

 public ObservableCollection<Item> Chapters { get; set; } = new();
  

        public class Item
        {
            public int id { get; set; }
            public string date { get; set; }
            public string title { get; set; }
            public string description { get; set; }
            public string URL { get; set; }
        }

        public class Root
        {
            public List<Item> items { get; set; }
        }

Deserializing json file and convert it to observableCollection:

var text = File.ReadAllText(@"C:\Users\Carlos\Desktop\test.json");
Chapters = new ObservableCollection<Item>(JsonConvert.DeserializeObject<Root>(text).items.ToList());

I try uptate the collection, but Datagrid just is updated when scrolling:

  private void btnCadena_Click(object sender, RoutedEventArgs e)
        {
            Chapters[2].title = "test";
        }

MainWindow.xaml:

<controls:DataGrid  x:Name="DgChapters"vItemsSource="{x:Bind Chapters}"/>

Thanks in advance

CodePudding user response:

Hi you can implement an interface. INotifyPropertyChanged. The interface makes the data update automatically when something changes in a list. The ObservableCollection is the right step :)

CodePudding user response:

ObservableCollection notifies the change in the collection, not the change inside each item.

I'd use the CommunityToolkit.Mvvm NuGet package to notify the changes inside each item.

// The class needs to be partial for the CommunityToolkit.Mvvm.
public partial class Item : ObservableObject
{
    [ObservableProperty]
    // The CommunityToolkit.Mvvm will automatically generate an UI-interactive
    // "ID" property for you.
    private int id;

    [ObservableProperty]
    // Same here. A "Title" property will be auto-generated.
    private string title = string.Empty;
}
  • Related