Question

I'm trying to obtain a DataGrid in my View from some DATA in my Model. I think i must reorganize the DATA in my ViewModel to display them in my View. I'm new in MVVM and I'd like to understand 2 points of the question:

  1. Taking in mind that I do not know neither the number of the rows, neither the number of the columns, what kind of data holder i should use? ObservableCollection<>? More in detail each row will have an item, and each column will have an aspect of the item.
  2. How can I set the Headers of my DataGrid?

The rows should apperar like 1,2,3... The columns should have their specific names.

This is my try:

MainWindow.xaml:

<DataGrid AutoGenerateColumns="false" ItemsSource="{Binding MyTable}" />

MainWindowViewModel.cs:

private ObservableCollection<List<MyItem>> _myTable;
public class MyItem
{
    public MyItem(string value)
    {
        Value= value;
    }
    public string Value{ get; set; }
}
public ObservableCollection<List<MyItem>> MyTable
{
    get
    {
        return _myTable;
    }

    set
    {
        _myTable = value;
        RaisePropertyChanged("MyTable");
    }
}

The execute of the comand is:

private void DisplayDataTableExecute()
    {
        MyTable = new ObservableCollection<List<MyItem>>();
        var temp = new List<MyItem>();
        temp.Add(new MyItem("one"));
        temp.Add(new MyItem("two"));
        temp.Add(new MyItem("three"));
        MyTable.Add(temp);
        temp = new List<MyItem>();
        temp.Add(new MyItem("ONE"));
        temp.Add(new MyItem("TWO"));
        temp.Add(new MyItem("THREE"));
        MyTable.Add(temp);
    }

When i use the AutoGenerateColumns="false" I only see some rows (the correct number but empty) when i use the AutoGenerateColumns="true" i see the properties of the table (Capacity and Count).

I really need some help, because i can't find a solution.

Was it helpful?

Solution

There are two main issues here:

First: You can't use AutoGenerateColumns = "false" without setting up columns. You'll need to map these through yourself, ie:

<DataGrid AutoGenerateColumns="false" ItemsSource="{Binding MyTable}" >
    <DataGrid.Columns>
        <DataGridTextColumn Header="Value"  Binding="{Binding Value}"/>
    </DataGrid.Columns>
</DataGrid>

Note that you can just set AutoGenerateColumns="true" instead, which will give you one column per property in your class.

Second: You will need to make your class (class MyItem) implement INotifyPropertyChanged if you want to have changes made in code reflected in the UI.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top