C# - WPF / WP从数据库绑定 - 正确的方法? MVVM

时间:2015-05-11 03:43:51

标签: c# wpf mvvm binding observablecollection

我们说这个类是模型(从中生成的数据库):

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
}

ViewModel 中,我有一个ObservableCollection客户,它拥有数据库中的所有客户:

ObservableCollection<Customer> Customers;

&#34;顾客&#34;从数据库中填充。

视图中,ListBox将从Customers:

填充
<ListBox ItemsSource="{Binding Customers}" />

这是问题所在。假设我想将新客户插入数据库,我应该采取什么方法来通过UI跟踪更改:

重置ItemsSource :(目前使用此方式 - 最糟糕的方法)

ListBoxExample.ItemsSource = null;
ListBoxExample.ItemsSource = Customers;

通过ObservableCollection客户跟踪更改

例如,如果我想在数据库中插入内容,请将其插入到Customers中,并且会通知UI有关更改的信息。

还有哪些其他选择?

实现以下目标的最佳MVVM方法是什么:

  • 解析JSON数据并将其插入本地数据库
  • 从本地数据库中检索数据并用它填充ListBox / ListView
  • 如果将新数据插入数据库或删除/更改项目,请更新ListBox / ListView
  • 中的更改

如果我想在数据库中添加项目,我只需将项目添加到客户列表并将其添加到数据库。但是,让我们说我从数据库,可观察集合&#34;客户&#34;中删除了一个对象。没有得到通知,并且将不同步(UI也不会更新)。有没有办法深入挖掘MVVM结构,而不是在可观察集合和数据库中添加/删除/更改项目,以某种方式使可观察集合跟踪数据库中的更改(例如,如果通过其他应用程序完成更改)。

1 个答案:

答案 0 :(得分:0)

嗯,我不知道你是否需要一个解决方案,但根据你最后的评论,你不满意......我将说明我的方法。

public class CustomersVm : INotifyPropertyChange
{ // just to point out, that you're using a VM class here   
   private ObservableCollection _customers;
   public ObservableCollection Customers
   { // since you're binding this to your listbox, DON'T change the reference during runtime
       get { return _customers ?? (_customers = new ObservableCollection());
   }

   // here comes your loading logic
   public void RefreshCustomers()
   {
       var customers = LoadCustomersFromDb(); // contains now a result set of model classes

       Customers.Clear(); //Clear the collection instead of creating it again.
       foreach(var customer in customers)
           Customers.Add(customer);
   }
}

现在在XAML中使用,如果DataContext的{​​{1}}设置为Window的实例,则该工作正常。 (注意:为了更一般,父元素的CustomersVm需要像这样设置。)

DataContext
相关问题