【问题标题】:WPF databinding to datagrid and entity framework database first首先将 WPF 数据绑定到数据网格和实体框架数据库
【发布时间】:2014-04-19 20:06:11
【问题描述】:

使用 Database First 方法,我在我的 wpf 项目中创建了实体(使用实体框架),所以我有 edmx 文件。

来自 MSDN: EF 使用 T4 模板从您的模型生成代码。随 Visual Studio 提供或从 Visual Studio 库下载的模板用于一般用途。这意味着从这些模板生成的实体具有简单的 ICollection 属性。但是,在使用 WPF 进行数据绑定时,最好将 ObservableCollection 用于集合属性,以便 WPF 可以跟踪对集合所做的更改。为此,我们将修改模板以使用 ObservableCollection。

所以我按照本教程将实体更改为具有 ObservableCollection 属性: http://msdn.microsoft.com/en-us/data/jj574514.aspx(章节更新数据绑定代码生成)

在带有 Visual Studio 的 WPF 视图(在 xaml 文件中)中,我添加了一个 DataGrid 并添加了以下代码:

private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
   using (SIEntities siContext = new SIEntities())
   {
      var query = from p in siContext.Customers
                  select p;

      dataGrid.ItemsSource = query.ToList();
    }
}

首先,要了解如何插入数据,我想从代码中在数据库中插入一个新客户,所以我有这个方法:

private void Button_Click_1(object sender, RoutedEventArgs e)
{
   using (SIEntities siContext = new SIEntities())
   {
         Customer cust1 = new Customers();
         cust1.Name = "Pippo";
         cust1.City = "London";
         siContext.Customers.Add(cust1);
         siContext.SaveChanges();
         dataGrid.Items.Refresh();
    }
 }

使用这段代码,我可以在数据库中插入一个新行,但我在数据网格中看不到这个新行。

在 xaml 文件中,我为 datagird 提供了以下内容:

<DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="43,65,0,0" VerticalAlignment="Top" Height="234" Width="423"/>

为什么?它没有绑定到实体的dataGrid? 如何在数据网格中显示添加到数据库中的新行?

谢谢

【问题讨论】:

    标签: wpf visual-studio-2010 entity-framework data-binding wpfdatagrid


    【解决方案1】:

    我会更改您使用 WPF 的方法以使用 MVVM 设计模式。您可以阅读http://msdn.microsoft.com/en-us/magazine/dd419663.aspx 了解更多信息。

    您的 DataGrid 绑定到查询结果。使用您使用的方法,您需要重新查询数据库并将 ItemsSource 重置为返回的结果。因此,按照您的模式,您需要进行以下更改:

    private void Window_Loaded_1(object sender, RoutedEventArgs e)
    {
       RefreshCustomers();
    }
    
    private void RefreshCustomers()
    {
       using (SIEntities siContext = new SIEntities())
       {
          var query = from p in siContext.Customers
                      select p;
    
          dataGrid.ItemsSource = query.ToList();
        }
    }
    
    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
       using (SIEntities siContext = new SIEntities())
       {
             Customer cust1 = new Customers();
             cust1.Name = "Pippo";
             cust1.City = "London";
             siContext.Customers.Add(cust1);
             siContext.SaveChanges();
        }
    
        RefreshCustomers();
    }
    

    【讨论】:

    • 问题。为什么不创建一个公共Customers 变量,它是List&lt;Customers&gt; 的列表,将DataGrid 源绑定到该列表,然后在Button_Click_1 上将新客户添加到List&lt;Customers&gt; 变量并刷新数据网格源?这样您就不必每次都查询。
    • 是的,您也可以这样做。如果您打算这样做,您可能应该只使用我在第一段中推荐的完整 MVVM。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多