Paul Gibson
Paul Gibson

Reputation: 634

C# WPF Datagrid binding to ObservableCollection Members

I'm trying to find a way to bind a WPF datagrid to an unknown number of strings that I read from a tab delimited text file. I have a view that I set the datacontext for in the code behind, and I figured that I would just set up the datagrid in the constructor code like this:

public MainWindow(FileParametersViewModel vm)
{
    InitializeComponent();
    DataContext = vm;
    dataGrid.ItemsSource = vm.lParams;
    for (int i = 0; i < vm.ParamNames.Count(); i++)
    {
        DataGridTextColumn col = new DataGridTextColumn();
        col.Binding = vm.lParams.pArray[i];
        col.Header = vm.ParamNames[i];
        dataGrid.Columns.Add(col);
    }
}

The ViewModel has an ObservableCollection lParams which I want to bind the datagrid to:

private ObservableCollection<FileSheetParameters> _lParams;
public ObservableCollection<FileSheetParameters> lParams
{
    get { return _lParams; }
    set
    {
        if (value != _lParams)
        {
            _lParams = value;
            NotifyPropertyChanged("lParams");
        }
    }
}

Each column will be bound to a member of a List within the FileSheetParameters (pArray):

public class FileSheetParameters
{
    public FileSheetParameters()
    {
        SheetExists = false;
        IsPlaceholder = false;
        pArray = null;
    }

    public bool SheetExists { get; set; }
    public bool IsPlaceholder { get; set; }
    public List<string> pArray { get; set; }
}

I populate the List from each line of the text file as I read it in.

My problem is that I can't actually reference lParams.pArray as I do in the first code block. I get a compile time error (and the red squiggly as well) that "ObservableCollection does not contain a definition for 'pArray'. But pArray is a member of the class of things that are in the collection . . . What am I doing wrong?

If I just set the Items source of the data grid, and don't do any column specific binding then I get an empty grid with a last column that is titled pArray and each cell says "(Collection)" . . . I have used a DataTable instead of an ObservableCollection, but that behavior is not what I like.

Upvotes: 0

Views: 404

Answers (1)

Paul Gibson
Paul Gibson

Reputation: 634

This one bugged me all night, and I just found the solution:

The binding command in the code behind should look like this:

   string path = String.Format("pArray[{0}]", i);
   col.Binding = new Binding(path);

And then the datagrid populates correctly.

Upvotes: 1

Related Questions