【问题标题】:Wrap an IEnumerable<T> with an ObservableCollection<T>用 ObservableCollection<T> 包装 IEnumerable<T>
【发布时间】:2011-05-15 22:03:18
【问题描述】:

从我的存储库中,我总是得到一个IEnumerable&lt;T&gt;

在我的 ViewModel 的 Ctor 或方法中,我想将我的实体包装成一个 ObservableCollection&lt;T&gt;,如下所示:

private ObservableCollection<CustomerViewModel> customerViewModels;

public BillingViewModel(IService service)
{
   ...
   IEnumerable<Customer> customers = service.GetCustomers();

   // that will not work because of a different type
   customerViewModels = new ObservableCollection(customers); 

}

你会怎么做?

【问题讨论】:

    标签: wpf mvvm viewmodel ienumerable


    【解决方案1】:

    如何将Customer 转换为CustomerViewModel?也许你只需要这样的东西:

    customerViewModels = new ObservableCollection<CustomerViewModel>(
        from c in customers
        select new CustomerViewModel(c)
    );
    

    【讨论】:

      【解决方案2】:

      假设您有某种从 Customer 到 CustomerViewModel 的转换:

      customerViewModels = new ObservableCollection<CustomerViewModel>
          (customers.Select(c => ConvertToViewModel(c)));
      

      【讨论】:

        猜你喜欢
        • 2012-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-14
        相关资源
        最近更新 更多