WPF使用现有ItemsSource将对象添加到ListBox [英] WPF Adding an object to ListBox with existing ItemsSource
问题描述
嘿,我有一个列表框,我将ItemsSource设置为数据库中对象的ObservableCollection,并且需要在此列表的末尾添加一个对象.但是我一直收到无效的操作异常.不知何故,我的列表框正在使用中(在我看来,这是一个给定的,因为它已经显示,并且里面已经有项目.)这是我的列表框代码:
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>
我首先像这样设置ItemsSource:
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:
在使用ItemsSource时,该操作无效.访问和修改 元素改为使用ItemsControl.ItemsSource.
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.
- 谢谢.
推荐答案
您需要将该项添加到项源,并且源应该是可观察的,以便ListBox
将新项考虑在内:
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);
这篇关于WPF使用现有ItemsSource将对象添加到ListBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!