Click to See Complete Forum and Search --> : Error in binding to ListBox


ahikamo
May 24th, 2010, 12:56 AM
Hi

I have a class that contains customers details and their products (the products is an ObservableCollection of product type).

In my xaml I create a DataTemplate for my customer class as follow:

<DataTemplate x:Key="CustomerTemplate">
<Grid>

<TextBlock Text="Customer ID" />
<TextBox Grid.Column="1" Text="{Binding CustomerID}" />

<TextBlock Grid.Row="1" Text="Customer Name" />
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding CustomerName}" />

<ListBox Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" ItemsSource="{Binding Products}">
<ListBox.Items>
<ListBoxItem Content="{Binding ProductName}" />
</ListBox.Items>
</ListBox>

</Grid>
</DataTemplate>


I use this DataTemplate in Content control:

<ContentControl Content="{Binding CurrentCustomer, ElementName=localView}"
ContentTemplate="{StaticResource CustomerTemplate}" />

When I run the application I got an exception:

{"Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead."}


I know that the problem relates to the binding of the ListBoxItems.

Any suggestions?

ahikamo
May 24th, 2010, 01:06 PM
I found the problem. I should create data template for each ListBoxItem as follow:

<ListBox Grid.Row="2" Grid.ColumnSpan="2" ItemsSource="{Binding Products}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ProductName}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

eclipsed4utoo
May 25th, 2010, 12:43 PM
Yeah, you can't bind to the ItemsSource and manually add ListBoxItems.