Reputation: 4570
I am wondering if there is a correct or sensible way of refreshing a DataGrid ItemSource from Entity Framework (i.e the Database)
I need to get the latest data from the table in the database as the data is being populated via a web service and not the WPF app itself.
I have used DataGrid.Items.Refresh() but to no prevail.
I could assign the Property of the Itemsource again, but then I need an event to happen on the datagrid to cause the update (unless that is wrong)
Anyone have any suggestions?
Thanks
Upvotes: 1
Views: 1509
Reputation: 14640
You just need to bind the DataGrid
properly.
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}">
<StackPanel>
<Button Content="Refresh" Click="Refresh_Click" />
<DataGrid ItemsSource="{Binding Items}"></DataGrid>
</StackPanel>
</Window>
Then clear the data binding and re-add the items, the UI will be updated automatically.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private readonly ObservableCollection<Item> _items = new ObservableCollection<Item>();
public ObservableCollection<Item> Items
{
get { return _items; }
}
private void Refresh_Click(object sender, RoutedEventArgs e)
{
using (var context = new AppContext())
{
var items = context.Items.ToArray();
// Clears the item source then re-add all items.
Items.Clear();
Array.ForEach(items, Items.Add);
}
}
}
Upvotes: 2