简体   繁体   English

WPF 实体框架数据网格刷新

[英]WPF Entity framework datagrid refresh

I started a new WPF project and on main Window I have a button.我开始了一个新的 WPF 项目,在主窗口上我有一个按钮。 When I click it, I show a new window that displays as follows: 1 textBox (named tbTax) 1 Add Button 1 DataGrid (named dbGrid)当我点击它时,我会显示一个新窗口,显示如下: 1 textBox(名为 tbTax) 1 添加按钮 1 DataGrid(名为 dbGrid)

I obtained the DataGrid, by going to DataSources tab, and DRAG/DROP from there a table on the form/window.我通过转到 DataSources 选项卡获得了 DataGrid,然后从窗体/窗口上的一个表中拖放/拖放。 When I run the app, it all works as planned.当我运行该应用程序时,一切都按计划进行。 In the second window I see in the grid all my records from the database table.在第二个窗口中,我在网格中看到了数据库表中的所有记录。

NOW: I did the Adding code for the "Add button".现在:我为“添加按钮”添加了代码。 So when the user enters some text in the textBox (tbTax) and clicks on the Add button, the following code follows:因此,当用户在 textBox (tbTax) 中输入一些文本并单击 Add 按钮时,以下代码如下:

 using (MyEntities context = new MyEntities())
            {
                TAX tax = new TAX();
                tax.TAX1 = decimal.Parse(tbTax.Text);
                context.TAXs.Add(tva);
                context.SaveChanges();
                tbTax.Text = "";
                dbGrid.Items.Refresh();
            }

So it should be obvious: I add an item to the database table through the entity framework.所以应该很明显了:我通过实体框架向数据库表中添加了一个项目。 But even if I added the refresh part at the end of the code... the grid does not refresh.但即使我在代码末尾添加了刷新部分……网格也不会刷新。 So only if I exit the window and re-show it, only then I can see the new item I just Added.所以只有当我退出窗口并重新显示它时,我才能看到我刚刚添加的新项目。

EDIT Following the drag/drop I ended up with this:编辑在拖放之后,我最终得到了这个:

--XAML-- --XAML--

 <DataGrid x:Name="tAXDataGrid" AutoGenerateColumns="False" EnableRowVirtualization="True" ItemsSource="{Binding}" Margin="10,157,10,35" RowDetailsVisibilityMode="VisibleWhenSelected">
            <DataGrid.Columns>
                <DataGridTextColumn x:Name="tAXColumn1" Binding="{Binding TAX}" Header="TAX" Width="SizeToHeader"/>
            </DataGrid.Columns>
        </DataGrid>

--XAML.cs-- --XAML.cs--

  private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            TestXXX.ArtDataSet artDataSet = ((TestXXX.ArtDataSet)(this.FindResource("artDataSet")));
            // Load data into the table TAX. You can modify this code as needed.
            TestXXX.ArtDataSetTableAdapters.TAXTableAdapter artDataSetTAXTableAdapter = new TestXXX.ArtDataSetTableAdapters.TAXTableAdapter();
            artDataSetTAXTableAdapter.Fill(artDataSet.TAX);
            System.Windows.Data.CollectionViewSource tAXViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("tAXViewSource")));
            tAXViewSource.View.MoveCurrentToFirst();
        }

Also, my Context is declared separately另外,我的上下文是单独声明的

namespace TestXXX
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class ArtEntities : DbContext
    {
        public ArtEntities()
            : base("name=ArtEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<BOOK> BOOKs { get; set; }
        public DbSet<TAX> TAXs { get; set; }
    }
}

and the TAX class is和 TAX 类是

namespace TestXXX
{
    using System;
    using System.Collections.Generic;

    public partial class TAX
    {
        public TAX()
        {
            this.BOOKs = new HashSet<BOOK>();
        }

        public int ID { get; set; }
        public Nullable<decimal> TAX1 { get; set; }

        public virtual ICollection<BOOK> BOOKs { get; set; }
    }
}

What is wrong with this?这有什么问题? How can I fix it?我该如何解决?

First of all, I assume you are only in a learning stage, as putting all layers into UI control is not a good idea.首先,我假设您只是处于学习阶段,因为将所有层都放入 UI 控件中并不是一个好主意。 Data layer (communication with database) should be separated from model and model should be separated from view.数据层(与数据库通信)应与模型分离,模型应与视图分离。 There is of course many other designs, but separation is a core issue in all of them.当然还有许多其他设计,但分离是所有设计的核心问题。

As you are using WPF, you should know the ObservableCollection contained in System.Collection.ObjectModel.当您使用 WPF 时,您应该知道 System.Collection.ObjectModel 中包含的 ObservableCollection。 This collection notifies data user (mostly UI controls in wpf) about changes in collection as adding, removing etc.此集合通知数据用户(主要是 wpf 中的 UI 控件)有关集合中的更改,如添加、删除等。

So what you need to do is set ItemSource of DataGrid with ObservableCollection.所以你需要做的是用ObservableCollection设置DataGrid的ItemSource。 All you need to do next is only add tax item into this collection and save it to the database.您接下来需要做的只是将税项添加到此集合中并将其保存到数据库中。 Nothing more.而已。

The solution seems to be simple after all... In the CS file of the Window毕竟解决方案似乎很简单......在Window的CS文件中

 public partial class NewTAX : Window
    {
        ArtEntities db;

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            db = new ArtEntities();
            dbgrid.ItemsSource = db.TAXs.ToList();
        }

... then after adding a new item, just set the ItemSource AGAIN like: ...然后在添加新项目后,只需将 ItemSource AGAIN 设置为:

        using (MyEntities context = new MyEntities())
        {
            TAX tax = new TAX();
            tax.TAX1 = decimal.Parse(tbTax.Text);
            context.TAXs.Add(tva);
            context.SaveChanges();
            tbTax.Text = "";
            dbgrid.ItemsSource = db.TAXs.ToList();
        }

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

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