Error setting ItemsSource on DataGrid

Oct 1, 2008 at 12:05 PM
I am trying to use the following DataTemplate to bind to my view model that exposes an ObservableCollection of Products:

<DataTemplate DataType="{x:Type local:ProductsPresentationModel}">
         
        <dg:DataGrid  ItemsSource="{Binding Products}">           
           
            <dg:DataGridTextColumn DataFieldBinding="{Binding Id}" Header="Product Id"></dg:DataGridTextColumn>
            <dg:DataGridTextColumn DataFieldBinding="{Binding Name}" Header="Product Name"></dg:DataGridTextColumn>           
           
         </dg:DataGrid>
    
</DataTemplate>


I get the error 'DataGridTextColumn' object cannot be added to 'DataGrid'. Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.'
If I use a ListView and set the ItemsSource then I do not get this error and updating the Products collection causes the list to automatically be updated with the changes.:

<ListView ItemsSource="{Binding Products}">
 <ListView.ItemTemplate>
  <DataTemplate>
   <TextBlock Text="{Binding Name}" ></TextBlock>
  </DataTemplate>
 </ListView.ItemTemplate>
</ListView> 

 

 

 


Can anyone help me implement this with the DataGrid?
I am not using a code behind file as I am using the Model View View-Model pattern.

Coordinator
Oct 1, 2008 at 4:52 PM

Hi DJM,

I think the problem may just be that you forgot to put the columns in the DataGrid.Columns collection.  Try this:

<DataTemplate DataType="{x:Type local:ProductsPresentationModel}">
         
        <dg:DataGrid  ItemsSource="{Binding Products}">           
            <dg:DataGrid.Columns>
                <dg:DataGridTextColumn DataFieldBinding="{Binding Id}" Header="Product Id"></dg:DataGridTextColumn>
                <dg:DataGridTextColumn DataFieldBinding="{Binding Name}" Header="Product Name"></dg:DataGridTextColumn>            
            </dg:DataGrid.Columns>            
         </dg:DataGrid>
    
</DataTemplate>

Let me know if that fixes the issue or not.

Thanks!
Samantha

Oct 2, 2008 at 10:54 AM
Hi Samantha,

That was indeed the error. It now works fine.

Many thanks,

DJM