C# WPF数据网格在INSERT元素到源之后不更新

C# WPF数据网格在INSERT元素到源之后不更新,c#,.net,wpf,entity-framework,data-binding,C#,.net,Wpf,Entity Framework,Data Binding,我是WPF的新手。我尝试做一个数据网格,它与我的实体框架模型表绑定在一起。我的表名是:Words。我在试着编一本简单的字典。 Im使用SQL Server Compact、WPF、实体框架 但是,从表中删除记录后,它工作正常。。。来自DataGrid desapers的行 您能告诉我为什么在将记录添加到实体之后,它们没有插入到DataGrid中吗? 关闭程序并再次打开后,记录位于DataGrid中 以下是我的DataGrid窗口代码: <Grid> <Grid>

我是WPF的新手。我尝试做一个数据网格,它与我的实体框架模型表绑定在一起。我的表名是:Words。我在试着编一本简单的字典。 Im使用SQL Server Compact、WPF、实体框架

但是,从表中删除记录后,它工作正常。。。来自DataGrid desapers的行

您能告诉我为什么在将记录添加到实体之后,它们没有插入到DataGrid中吗? 关闭程序并再次打开后,记录位于DataGrid中

以下是我的DataGrid窗口代码:

<Grid>

<Grid>
        <DataGrid IsReadOnly="True" AutoGenerateColumns="False" Name="dataGrid" DataContext="{Binding }" ItemsSource="{Binding}" Margin="0,90,0,0">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Sentence" Binding="{Binding Path=sentence}" />
                <DataGridTextColumn Header="Translation" Binding="{Binding Path=translation}" />
                <DataGridTemplateColumn Header="Operations">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Delete" Click="Button_Click" Tag="{Binding Path=id}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
        <TextBox Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="sentence" VerticalAlignment="Top" Width="153" />
        <TextBox Height="23" Margin="171,12,131,0" Name="translations" VerticalAlignment="Top" AcceptsReturn="True" />
        <Button Content="Add" Height="23" HorizontalAlignment="Left" Margin="90,41,0,0" Name="addBtn" VerticalAlignment="Top" Width="75" Click="addBtn_Click" />
    </Grid>
我的数据库表的结构:

Words
---------------
id uniqueidentifier rowguidcol not null primary key,
sentence nvarchar(255) not null,
translation nvarchar(255) not null,

我的最佳猜测是DataContext被设置为项目的副本,而不是指向现有项目

与其将DataContext设置为某个项,不如将其绑定到该项。这将使DataContext指向该项,而不是复制它

Binding b = new Binding();
b.Source = db.Words;
dataGrid.SetBinding(DataGrid.ItemsSourceProperty, b);
编辑


刚刚注意到您直接绑定到上下文。默认情况下,这不会引发CollectionChanged事件来告诉DataGrid项目已更改,因此DataGrid不会尝试重新读取其项目资源


尝试手动刷新绑定(
dataGrid.GetBindingExpression(dataGrid.ItemsSourceProperty).UpdateTarget()
),或者通过重新查询数据库来刷新上下文(请参见示例)

谢谢您的回复,但它仍然没有解决我的问题…:/刚刚注意到您直接绑定到上下文。默认情况下,这不会引发CollectionChanged事件来告诉DataGrid项目已更改,因此DataGrid不会尝试重新读取其项目资源。尝试手动在Bindings上引发PropertyChanged事件,如果您告诉我如何才能做到这一点,那将是非常棒的?我是WPF的新手。这是我用WPF写东西的第二天。@nosbor我相信它类似于
BindingOperations.GetBindingExpressionBase(dataGrid,dataGrid.ItemsSourceProperty).UpdateTarget()我的猜测是,即使您添加了该项,上下文也不会得到更新,直到您重新查询数据库之后。例如,请参见以下链接:
Binding b = new Binding();
b.Source = db.Words;
dataGrid.SetBinding(DataGrid.ItemsSourceProperty, b);