0

I am new in MVVM and WPF world. I've been looking for an answer to this question with no luck. I wanna bind a datagrid using an ObservableCollection which is in my ViewModel class but the data that feeds my ObservableCollection comes from 2 different tables looking something like this:

Table Location:

 - id
 - name
 - locationTypeId
 - isActive

Table LocationType:

 - id
 - name
 - isActive

So in my ViewModel class I'm not able to have something like this:

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

without modifiying my Model class to something like this:

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;}

}

All the examples I've seen so far for databinding and viewmodels use as example a simple class that comes from a table as a type for the observablecollection.

Thanks in advance.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
The Geox
  • 1
  • 1

2 Answers2

2

Just create an additional ViewModel that will serve as Data Item for your rows:

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;}

}

Then:

public class LocationListViewModel
{
   ObservableCollection<LocationViewModel> dataSource {get;set;}
}
Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154
  • Thanks that's something that would work but is there any other way that don't force me to create a class every time I have to do the binding in a similar situation? I would also like to create dynamic views allowing a user to select the columns which he/she would like to see. Is any other way that could help me to solve my problems without having to create a class in the fly? – The Geox Jul 03 '13 at 00:46
0

I found a solution mixing 2 approaches:

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

plus the anwser by Fredrik Hedblad to the question:

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

Community
  • 1
  • 1
The Geox
  • 1
  • 1