如何在GridView中数据绑定两个表?

时间:2016-04-27 21:22:37

标签: wpf sqlite data-binding mvvm-light observablecollection

基本上,我需要加入两个ObservableCollections,例如ProductBrandInfo,其中Product模型具有非正式定义foreign key到{ {1}}。这些模型使用BrandInfo来保持数据持久性。

我希望在Sqlite-Net中显示两者的组合,这将是未来在其他GridView屏幕上进行数据操作的基础。

我当前的设置包含通过Xaml类绑定的数据,通过viewModel模型获取数据。 Product的{​​{1}}实例为viewModel,并且正常有效。

根据我的阅读,我可能需要使用ObservableCollection或者可能创建一个代表ProductCompositeCollection的{​​{1}}的模型。考虑到join不支持Product和其他BrandInfo等外键,我不确定如何使用Sqlite-Net。我也不确定这两种模型的非数据库存储组合是不是一个好主意。任何建议或片段都可以帮助我解决问题!

提前致谢!

一些代码:

MainWindowViewModel.cs

Entity Framework

Product.cs

ORM's

BrandInfo.cs

CompositeCollection

1 个答案:

答案 0 :(得分:1)

编辑我的初步答案完全基于对问题的误解。

由于我不熟悉SQLite,我不确定您的Product和BrandInfo模型是通过代码生成还是手动创建的。如果手动创建,您是否可以将BrandInfo属性添加到Product?如果可能,您可以使用linq加入product和brandinfo模型的集合,以创建可以在GridView中绑定的集合:

void Main()
{
    List<Product> products = new List<Product>() { new Product() {Id = 1, ItemName="Item1", BrandInfoFK=1}, new Product() {Id=2, ItemName="Item2", BrandInfoFK=2}};
    List<BrandInfo> brands = new List<BrandInfo>() { new BrandInfo() { Id = 1, BrandName="One"}, new BrandInfo() {Id = 2, BrandName="Two"}};


    List<Product> joinedProducts = products.Join(brands, p => p.BrandInfoFK, b => b.Id, (p, b) => new Product ()
    {
        Id = p.Id,
        ItemName = p.ItemName,
        Price = p.Price,
        BrandInfoFK = p.BrandInfoFK,
        BrandName = b.BrandName,
        BrandDescription = b.Description
    }).ToList();
}


public class Product {

    public int Id { get; set;}

    public string ItemName { get; set;}

    public double Price { get; set;}

    public int BrandInfoFK { get; set;}    

    // Brand properties
    public string BrandName {get; set;}

    public string BrandDescription {get; set;}
}

public class BrandInfo {
    public int Id { get; set;}

    public string BrandName { get; set;}

    public string Description { get; set;} 
}

我在这里使用List,但你可以很容易地适应ObservableCollection。此外,如果您不想/不想将BrandInfo属性添加到产品模型中,您可以创建一个派生自Product的类来添加这些属性吗?