简体   繁体   中英

WPF Adding an object to ListBox with existing ItemsSource

Hey I have a list box that I set the ItemsSource to be an ObservableCollection of objects from my database, and I need to add a single object at the end of this list. However I keep getting an invalid operation exception. Somehow my listbox is in use (which in my mind is a given as it is displayed and already have items inside.) Here is my code for the list box:

<ListBox x:Name="CarList" SelectionChanged="ItemSelected" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Background="{x:Null}">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel FlowDirection="LeftToRight" ItemHeight="300" ItemWidth="300"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>

        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Margin="10,10">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="35" />
                    </Grid.RowDefinitions>
                    <Image Grid.Row="0" Source="{Binding image_path}" VerticalAlignment="Stretch"/>
                    <Grid Grid.Row="1" Background="SteelBlue">
                        <TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" Margin="3" Text="{Binding model}"/>
                        <TextBlock HorizontalAlignment="Right" VerticalAlignment="Center" Margin="3" Text="{Binding price}"/>
                    </Grid>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>

And I first set the ItemsSource like so:

CarList.ItemsSource = CarController.GetAllCars();

And then want to add my custom object like this:

ListBoxItem carAdd = new ListBoxItem();
carAdd.Content = new CarModel{ image_path = "/../Assets/add-512.png", id=-1};
CarList.Items.Add(carAdd);

But alas the last operation fails with this message:

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

I have looked for a few other suggestions but all use strings and single bindings in their examples and thus I haven't been able to figure out what exactly to do. If anyone got a suggestion it would be much appreciated.

- Thanks.

You need to add the item to the items source, and the source should be observable so that the ListBox takes the new item into account:

var cars = new ObservableCollection<CarModel>(CarController.GetAllCars());
CarList.ItemsSource = cars;

...

var car = new CarModel{ image_path = "/../Assets/add-512.png", id=-1};
cars.Add(car);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM