C# WPF<-&燃气轮机;实体绑定

C# WPF<-&燃气轮机;实体绑定,c#,wpf,entity-framework,binding,C#,Wpf,Entity Framework,Binding,我在将数据源(数据库通过实体fw)中的数据更新到wpf窗口时遇到问题。我使用实体框架生成文件,因此我通过以下方式从数据库中访问数据: public partial class sampleWindow : Window { myEntity en = new myEntity(); public sampleWindow() { InitializeComponent(); Bind();

我在将数据源(数据库通过实体fw)中的数据更新到wpf窗口时遇到问题。我使用实体框架生成文件,因此我通过以下方式从数据库中访问数据:

public partial class sampleWindow : Window
    {
        myEntity en = new myEntity();
        public sampleWindow()
        {
            InitializeComponent();
            Bind();
        }

        private void Bind()
        {
            var list = from o in en.table select o;
            someDatagrid.ItemsSource = list.ToList();
        }
 //Gets the Load() extention method available for DbSet
    using System.Data.Entity;

        private void Bind()
        {
            myEntity.table.Load();
            /*Local returns an obvervable collection convenient for data binding. 
            This is a synchronized local view of your data. It means any item added , deleted and updated will be reflected in your controls.*/
            var obsColl = myEntity.table.Local;
            someDatagrid.ItemsSource = obsColl;
        }

首先,这个方法对于我的程序来说是足够的,在我对数据库做了一些操作之后,我正在刷新“Bind”方法,所以我的数据网格或组合中的数据是新鲜的。问题发生在我在不同的wpf窗口中更改数据库时。我已经读到,我应该实现可观察的接口,并使用load而不是itemsSource。我试着去做,但我很穷,我的尝试失败得很惨。有人能一步一步地告诉我,我应该怎么做吗?

您需要一个单例来管理您的数据,并使用ObservableCollection来公开数据。当集合被任何视图更改时,它将通知观察的所有订阅者,他们将自动更新

请参阅:XAML应用程序中的可绑定列表示例()
的示例您可能希望在您的实体实例中使用单例,如前面提到的锋利忍者。他的文章在他发布的链接中做了很好的解释。您需要使用可观察集合将ItemSource绑定到。当从可观察集合中添加或删除项目时,UI会自动收到通知。您将遇到的问题是没有.ToObservableCollection() 扩展方法内置于.net中,因此您必须实现自己的扩展方法

我使用这个扩展方法

 public static ObservableCollection<T> ToObservableCollection<T>(
        this IEnumerable<T> enumeration)
    {
        return new ObservableCollection<T>(enumeration);
    }

有很多比您的方法更好的方法(MVVM模式)来实现这一点。为了保持简单,可以通过以下方式完成:

public partial class sampleWindow : Window
    {
        myEntity en = new myEntity();
        public sampleWindow()
        {
            InitializeComponent();
            Bind();
        }

        private void Bind()
        {
            var list = from o in en.table select o;
            someDatagrid.ItemsSource = list.ToList();
        }
 //Gets the Load() extention method available for DbSet
    using System.Data.Entity;

        private void Bind()
        {
            myEntity.table.Load();
            /*Local returns an obvervable collection convenient for data binding. 
            This is a synchronized local view of your data. It means any item added , deleted and updated will be reflected in your controls.*/
            var obsColl = myEntity.table.Local;
            someDatagrid.ItemsSource = obsColl;
        }