If you are using the MVVM pattern, I think this is the best solution:
Create an ObservableCollecion in your ViewModel, which will be bound to the ItemSource in the DataGrid :
public ObservableCollection<T> bindableCollection;
Then retrieve data from your database, for example:
public void RefreshDataGrid(){ using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings[ "RecipeManager.Properties.Settings.RecipeManagerConnectionString"].ConnectionString)){ var fetchedData = conn.Query<Flavour>("select * from [Flavour]"); ConvertToDataTable(fetchedData); } }
The final step and the most important create function is to add IEnumerable to your ObservableCollection:
private void ConvertToObservableCollection(IEnumerable<Flavour> items){ ObservableCollection<Flavour> flavours = new ObservableCollection<Flavour>(); foreach (var item in items){ Flavour flavour = item as Flavour; flavours.Add(new Flavour(flavour.Name,flavour.Company,flavour.Shop,flavour.Amount)); } Flavours = flavours; }
I think this is a good approach for mvvm.
Michaล ลciborski
source share