WPF数据网格如何从实体框架中刷新Itemsource
本文关键字:框架 实体 刷新 Itemsource 数据 数据网 网格 WPF | 更新日期: 2023-09-27 18:15:32
我想知道是否有一种正确或明智的方式从实体框架(即数据库)刷新DataGrid ItemSource
我需要从数据库中的表中获取最新的数据,因为数据是通过web服务填充的,而不是WPF应用程序本身。
我已经使用了DataGrid.Items.Refresh(),但没有占上风。
我可以再次分配Itemsource的属性,但随后我需要在数据网格上发生一个事件来导致更新(除非这是错误的)
谁有什么建议?谢谢
您只需要正确地绑定DataGrid
。
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}">
<StackPanel>
<Button Content="Refresh" Click="Refresh_Click" />
<DataGrid ItemsSource="{Binding Items}"></DataGrid>
</StackPanel>
</Window>
然后清除数据绑定,重新添加项,UI将自动更新。
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);
}
}
}