【问题标题】:Bind data from 2 tables to datagrid using mvvm使用 mvvm 将 2 个表中的数据绑定到数据网格
【发布时间】:2026-02-18 18:20:06
【问题描述】:

我是 MVVM 和 WPF 世界的新手。我一直在寻找这个问题的答案,但没有运气。 我想使用我的 ViewModel 类中的 ObservableCollection 绑定数据网格,但是为我的 ObservableCollection 提供数据的数据来自两个不同的表,看起来像这样:

Table Location:

 - id
 - name
 - locationTypeId
 - isActive

Table LocationType:

 - id
 - name
 - isActive

所以在我的 ViewModel 类中我无法拥有这样的东西:

public class LocationListViewModel
{
   ObservableCollection< Model.Location> dataSource;
}

无需将我的 Model 类修改为以下内容:

public class Location
{

  public Int32 id {set; get;}
  public String name {get; set;}
  public Int32 locationTypeId {set; get;}
  public Boolean isActive {get; se;}

  //added property to get the location name

  public String locationTypeName {set; get;}

}

到目前为止,我所看到的所有数据绑定和视图模型示例都使用一个简单的类作为示例,该类来自一个表作为 observablecollection 的类型。

提前致谢。

【问题讨论】:

    标签: wpf data-binding mvvm datagrid


    【解决方案1】:

    只需创建一个额外的 ViewModel 用作您的行的数据项:

    public class LocationViewModel: ViewModelBase
    {
    
      public Int32 id {set; get;}
      public String name {get; set;}
      public Int32 locationTypeId {set; get;}
      public Boolean isActive {get; se;}
    
      //added property to get the location name
    
      public String locationTypeName {set; get;}
    
    }
    

    然后:

    public class LocationListViewModel
    {
       ObservableCollection<LocationViewModel> dataSource {get;set;}
    }
    

    【讨论】:

    • 谢谢,这是可行的方法,但有没有其他方法可以在每次我必须在类似情况下进行绑定时不强制我创建一个类?我还想创建动态视图,允许用户选择他/她想要查看的列。有没有其他方法可以帮助我解决我的问题,而无需即时创建课程?
    【解决方案2】:

    我找到了混合两种方法的解决方案:

    http://paulstovell.com/blog/dynamic-datagrid

    加上 Fredrik Hedblad 对这个问题的回答:

    How do I bind a WPF DataGrid to a variable number of columns?

    【讨论】: