I'm developing a WPF app based on MVVM. I want to bind a list of strings to column header ie., if the list contains "abc", "xyz", "pqr", then my DataGrid
should have three columns with header abc, xyz, pqr. Here is my class to which I am binding the datagrid. The rows are stored in ObservableCollection<List<string>>
where each element of ObservableCollection
is a List of string which forms the cells of the rows.
public class Resource
{
private ObservableCollection<string> columns;
public ObservableCollection<string> Columns
{
get
{
return columns;
}
set
{
columns = value;
}
}
private ObservableCollection<List<string>> row;
public ObservableCollection<List<string>> Row
{
get
{
return row;
}
set
{
row = value;
}
}
public Resource()
{
List<string> a = new List<string>();
a.Add("1");
a.Add("2");
List<string> b = new List<string>();
b.Add("11");
b.Add("21");
Row = new ObservableCollection<List<string>>();
Row.Add(a);
Row.Add(b);
Columns = new ObservableCollection<string>();
Columns.Add("Hello");
Columns.Add("World");
}
}
I have searched Internet a lot but couldn't find anything with a working example. I really need to bind DataGrid
by this method only.
DataTemplate
per data-type instead of trying a "one size fits all" solution that won't really be suitable for anything but the very basic string-only data types. – Federico Berasategui