简体   繁体   中英

How to call the ItemSource of a DataGrid to refresh it?

I am using would like to use WPF DataGrid to display a list of instances of eg a class Animal that I store during the life of my application (say I add/remove animals to my list) in an attribute of my main Window

public List<Animal> _animals
public class Animal {
    public int ID { get; set; }
    public strng name { get; set; }
}

I added the DataGrid to my XAML as such

<DataGrid Name="AnimalGrid"></DataGrid>

Then linked it to a function LoadAnimals() when initializing my window :

AnimalGrid.ItemsSource = LoadAnimals();
public List<Animal> LoadAnimals() {
    return _animals;
}

I want the Data grid to update/refresh. More precisely I pretty much only want the data grid to call LoadAnimal function again. I have tried AnimalGrid.Items.Refresh() but it does not work.

Any suggestions ?

WPF bindings don't work by magic alone, the code somehow needs to emit the right events for the data grid to update.

To update in response to changes in the collection (additions / deletions), use ObservableCollection<Animal> as your ItemsSource , that will fire the proper events to update the data grid when the collection changes.

You will also have to implement INotifyPropertyChanged in your Animal class if you want the grid to respond to changes in the ID and name properties for the individual rows.

Also, your LoadAnimals() function doesn't seem to do anything, since it just checks for null and then returns null in that case. +1 for the comment about MVVM, it is better in the long run to bind your ItemsSource to some property in a class (view model) instead of setting it in the code behind.

If you are only adding removing elements from collection. Then you can use ObservableCollection

If you want to create a new collection or want to update properties of objects inside collection. Implement INotifyPropertyChanged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM