I am using would like to use WPF DataGrid to display a list of instances of e.g. 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 yourItemsSource, that will fire the proper events to update the data grid when the collection changes.You will also have to implement
INotifyPropertyChangedin yourAnimalclass if you want the grid to respond to changes in theIDandnameproperties 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 yourItemsSourceto some property in a class (view model) instead of setting it in the code behind.