简体   繁体   English

WPF DataGrid如何从实体框架刷新项目源

[英]WPF DataGrid how to refresh Itemsource from Entity-Framework

I am wondering if there is a correct or sensible way of refreshing a DataGrid ItemSource from Entity Framework (ie the Database) 我想知道是否存在从实体框架(即数据库)刷新DataGrid ItemSource的正确或明智的方法

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. 我需要从数据库表中获取最新数据,因为这些数据是通过Web服务而不是WPF应用程序本身填充的。

I have used DataGrid.Items.Refresh() but to no prevail. 我使用了DataGrid.Items.Refresh(),但没有成功。

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) 我可以再次分配Itemsource的Property,但是然后我需要在datagrid上发生一个事件来引起更新(除非那是错误的)

Anyone have any suggestions? 有人有什么建议吗?

Thanks 谢谢

You just need to bind the DataGrid properly. 您只需要正确绑定DataGrid

<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. 然后清除数据绑定并重新添加项目,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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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