DataGrid and Dynamic DataViews

Apr 20, 2010 at 3:42 AM

I have been struggling for days trying to get working what I thought would be a piece of cake. I have a DataSet with multiple DataTables.  The tables and their underlying row names are navigable with a tree view. When the user clicks on a row name I want the field items for that row to be displayed in a DataGrid with the column names auto-generated. My expectation was that when the DG is bound to an ObservableCollection of DataRows (or their DataRowViews)  all of which share a common Table property, the DG would get the column headers from the Table and display the Row items in their appropriate GridBox. That of course is not what happens. The GB displays the column headers and data of the DataView object, not the underlying Items. 

I have tried many approaches (return the Table, build a new DataTable, return the DataView, return ObservableCollections of each etc.) but this is where I'm at now:

        #region Selected Row Display
        private ObservableCollection<DataRowView> _selectedRow = new ObservableCollection<DataRowView>();
        public ObservableCollection<DataRowView> SelectedRow
               return _selectedRow;
                //Get selected row view model from tree
                var x = this.Where(c=>((ManagedViewModel)c).IsSelected).ToArray();
                RowViewModel y = (RowViewModel)x[0];

                //Get the data model from the RVM
                RowElement re = (RowElement)y.DataElement;
                DataRow dr = re.Row;

                //Create a DataView
                DataColumn[] keys=dr.Table.PrimaryKey;
                string key = "["+keys[0].ColumnName + "] = '" + dr.ItemArray[keys[0].Ordinal].ToString()+"'";
                DataView dv = new DataView(dr.Table, key, keys[0].ColumnName, DataViewRowState.CurrentRows); 

                //Add the DataRowView to the OC
The XAML for the DG is just
   <WpfToolkit:DataGrid ItemsSource="{Binding}" 
                             SelectionMode="Extended" Height="219" 
                             HorizontalAlignment="Left" Name="dataGrid">

and in the code behind I set dataGrid.DataContext = vm.SelectedRow

Since I know it woks if I bind  a View Model of a data model, I thought perhaps if instantiated a view model for each table which all inherit from a common abstract base class, I could bind to an Observable<BaseClass> collection. Stymied again. The DG in this case displays the abstract base class fields (i.e nothing). Argh!!!

Can anyone tell me what I am doing wrong or if what I am trying to do is beyond the capability of the DataGrid?

Apr 21, 2010 at 5:33 PM

I figured this out and posted my solution here