CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    May 2010
    Posts
    4

    Question Error in binding to ListBox

    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?

  2. #2
    Join Date
    May 2010
    Posts
    4

    Resolved Re: Error in binding to ListBox

    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>

  3. #3
    Join Date
    Nov 2007
    Location
    .NET 3.5 / VS2008 Developer
    Posts
    624

    Re: Error in binding to ListBox

    Yeah, you can't bind to the ItemsSource and manually add ListBoxItems.
    ===============================
    My Blog

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured