WPF的DataGrid instert元素源后犯规更新元素、WPF、DataGrid、instert

2023-09-04 04:29:51 作者:笑忘身是客

我是新的WPF。我尝试做的是绑定与我的实体框架模型表中的数据网格。我的表的名称是:词。我试着做简单的字典。 即时通讯使用SQL Sever的紧凑型,WPF,实体框架。

然而,从表中删除的记录后,它正在确定...从DataGrid中desapers行

你能告诉我,为什么添加记录实体后,他们没有inseted到DataGrid中? 关闭程序后重新打开记录都在DataGrid中。

下面是数据网格窗口的我的code:

 <电网>

<电网>
        <的DataGrid的IsReadOnly =真的AutoGenerateColumns =FALSENAME =的数据网格的DataContext ={结合}的ItemsSource ={结合}保证金=0,90,0,0>
            < D​​ataGrid.Columns>
                < D​​ataGridTextColumn标题=句子绑定={绑定路径=一句}/>
                < D​​ataGridTextColumn标题=翻译绑定={绑定路径=翻译}/>
                < D​​ataGridTemplateColumn标题=操作>
                    < D​​ataGridTemplateColumn.CellTemplate>
                        <的DataTemplate>
                            <按钮内容=删除点击=Button_Click标签={绑定路径= ID}/>
                        < / DataTemplate中>
                    < /DataGridTemplateColumn.CellTemplate>
                < / DataGridTemplateColumn>
            < /DataGrid.Columns>
        < /数据网格>
        <文本框高度=23的Horizo​​ntalAlignment =左保证金=12,12,0,0NAME =一句VerticalAlignment =热门WIDTH =153/>
        <文本框高度=23保证金=171,12,131,0NAME =翻译VerticalAlignment =热门AcceptsReturn =真/>
        <按钮内容=添加高度=23的Horizo​​ntalAlignment =左保证金=90,41,0,0NAME =addBtnVerticalAlignment =热门WIDTH =75点击=addBtn_Click/ >
    < /网格>
 

下面是我的C#code:

 公共部分类AddWordWnd:窗口{
    静态dbEntities DB =新dbEntities();

    公共AddWordWnd(){
        的InitializeComponent();
        dataGrid.DataContext = db.Words;
        dataGrid.Visibility = System.Windows.Visibility.Visible;
    }

    私人无效Button_Click(对象发件人,RoutedEventArgs E){
        按钮BTN =发件人的按钮;
        的System.Guid二= System.Guid.Parse(btn.Tag.ToString());
        的MessageBox.show(ii.ToString());
        db.DeleteObject(db.Words.Single(W => w.id ==二));
        db.SaveChanges();
    }

    私人无效addBtn_Click(对象发件人,RoutedEventArgs E){
        的System.Guid GG = System.Guid.NewGuid();
        db.Words.AddObject(新字(){n = GG,一句= translations.Text,翻译= sentence.Text});
        db.SaveChanges();
        dataGrid.Items.Refresh();
    }
}
 
WPF 如何删除datagrid的最后一列 空列

我的数据库表的结构:

 词
---------------
ID唯一标识符ROWGUIDCOL不为空主键,
句子为nvarchar(255)不为空,
翻译为nvarchar(255)不为空,
 

解决方案

我最好的猜测是,在DataContext是越来越设置,而不是指向现有项目到你的项目的副本。

而不是

设置的DataContext的一个项目,绑定的到该项目。这将使而不是拷贝它的DataContext点的项目。

 绑定B =新的Binding();
b.Source = db.Words;
dataGrid.SetBinding(DataGrid.ItemsSourceProperty,B);
 

修改

只注意到你直接绑定到上下文。默认情况下,不提高CollectionChanged事件要告诉你的DataGrid中,该项目已发生变化,所以在DataGrid不会尝试重新读取它的ItemsSource。

尝试要么刷新手动绑定( dataGrid.GetBindingEx pression(DataGrid.ItemsSourceProperty).UpdateTarget()),或者通过重新查询数据库刷新背景(看this回答一个例子)

I'm new in WPF. I try to do a DataGrid which is binded with my entity framework model table. Name of my table is: Words. Im trying to do simple dictionary. Im using SQL Sever Compact, WPF, Entity framework.

However, after removing records from table it is working ok... rows from DataGrid desapers

Can you tell me why after adding records to entity they are not inseted to DataGrid? After turn off program and turn on again the records are in DataGrid.

Here is my code of DataGrid window:

<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>

Here is my c# code:

public partial class AddWordWnd : Window {
    static dbEntities db = new dbEntities();

    public AddWordWnd() {
        InitializeComponent();
        dataGrid.DataContext = db.Words;
        dataGrid.Visibility = System.Windows.Visibility.Visible;
    }

    private void Button_Click( object sender, RoutedEventArgs e ) {
        Button btn = sender as Button;
        System.Guid ii = System.Guid.Parse(btn.Tag.ToString());
        MessageBox.Show(ii.ToString());
        db.DeleteObject(db.Words.Single(w => w.id == ii));
        db.SaveChanges();
    }

    private void addBtn_Click( object sender, RoutedEventArgs e ) {
        System.Guid gg = System.Guid.NewGuid();
        db.Words.AddObject(new Words() { id = gg, sentence = translations.Text, translation = sentence.Text });
        db.SaveChanges();
        dataGrid.Items.Refresh();
    }
}

Structure of my database table:

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

解决方案

My best guess would be that the DataContext is getting set to a copy of your item, instead of pointing to the existing item.

Instead of setting the DataContext to an item, bind it to that item. This will make the DataContext point to the item, instead of copying it.

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

Edit

Just noticed you're binding directly to the context. By default, that doesn't raise the CollectionChanged event to tell your DataGrid that the items have changed, so the DataGrid doesn't try to re-read it's ItemsSource.

Try either refreshing the binding manually (dataGrid.GetBindingExpression(DataGrid.ItemsSourceProperty).UpdateTarget()), or refreshing the context by requerying the database (see this answer for an example)