WPF DataGrid如何从Entity-Framework刷新Itemsource

时间:2014-07-29 15:56:14

标签: c# wpf entity-framework datagrid

我想知道是否有正确或明智的方法从Entity Framework(即数据库)刷新DataGrid ItemSource

我需要从数据库中的表中获取最新数据,因为数据是通过Web服务而不是WPF应用程序本身填充的。

我使用过DataGrid.Items.Refresh(),但没有占上风。

我可以再次分配Itemsource的属性,但是我需要在datagrid上发生一个事件以引起更新(除非那是错误的)

有人有任何建议吗?

谢谢

1 个答案:

答案 0 :(得分:1)

您只需要正确绑定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);
        }
    }
}