WPF DataGrid在instert元素到源之后不会更新 [英] WPF DataGrid doesnt update after instert element to source

查看:163
本文介绍了WPF DataGrid在instert元素到源之后不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WPF中是新的。我尝试做一个与我的实体框架模型表绑定的DataGrid。我的名字是:单词。我试图做简单的字典。
我使用SQL Sever Compact,WPF,Entity框架。



但是,从表中删除记录后,它正在工作正常... DataGrid中的行



你能告诉我为什么在向实体添加记录之后,他们没有插入DataGrid?
关闭程序并再次打开后,记录在DataGrid中。



这是我的DataGrid窗口代码:

 < Grid> 

< Grid>
< DataGrid IsReadOnly =TrueAutoGenerateColumns =FalseName =dataGridDataContext ={Binding}ItemsSource ={Binding}Margin =0,90,0,0>
< DataGrid.Columns>
< DataGridTextColumn Header =SentenceBinding ={Binding Path = sentence}/>
< DataGridTextColumn Header =TranslationBinding ={Binding Path = translation}/>
< DataGridTemplateColumn标题=操作>
< DataGridTemplateColumn.CellTemplate>
< DataTemplate>
< Button Content =DeleteClick =Button_ClickTag ={Binding Path = id}/>
< / DataTemplate>
< /DataGridTemplateColumn.CellTemplate>
< / DataGridTemplateColumn>
< /DataGrid.Columns>
< / DataGrid>
< TextBox Height =23Horizo​​ntalAlignment =LeftMargin =12,12,0,0Name =sentenceVerticalAlignment =TopWidth =153/>
< TextBox Height =23Margin =171,12,131,0Name =translationsVerticalAlignment =TopAcceptsReturn =True/>
< Button Content =AddHeight =23Horizo​​ntalAlignment =LeftMargin =90,41,0,0Name =addBtnVerticalAlignment =TopWidth =75Click = addBtn_Click/>
< / Grid>

这是我的c#代码:

  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();
}
}

我的数据库表的结构:

 单词
---------------
id uniqueidentifier rowguidcol not null主键,
句子nvarchar(255)not null,
翻译nvarchar(255)not null,


解决方案

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



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

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

修改



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



尝试手动刷新绑定( dataGrid.GetBindingExpression(DataGrid.ItemsSourceProperty).UpdateTarget()),或通过重新查询数据库来刷新上下文(请参阅这个答案例如)


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)

这篇关于WPF DataGrid在instert元素到源之后不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆