我想在listview中添加我的項目。這是我的課程;如何在wpf應用程序的listview中添加項目?
FindFace.Show.Response response = await _api.Show_Face(lb_GalleryList.SelectedItem.ToString());
if (response.results.Count != 0)
{
List<FaceImages> faceImages = new List<FaceImages>();
for (int i = 0; i < response.results.Count; i++)
{
faceImages.Add(new FaceImages() { Face_id = response.results[i].person_id.ToString(), Face_thumbnail = LoadImage(response.results[i].thumbnail) });
}
lv_Photos.ItemsSource = faceImages;
}
而且這裏是我的xaml文件的樣子;
<ListView x:Name="lv_Photos" HorizontalAlignment="Stretch" VerticalAlignment="Top">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="5" HorizontalAlignment="Stretch" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<DataTemplate>
<StackPanel Orientation="Vertical" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Image Source="{Binding Face_thumbnail}" HorizontalAlignment="Stretch" VerticalAlignment="Top" Stretch="UniformToFill" />
<TextBlock Text="{Binding Face_id}" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" />
</StackPanel>
</DataTemplate>
</ListView>
但是,當我試圖把faceImages放在ItemsSource這裏;
lv_Photos.ItemsSource = faceImages;
應用程序使
An exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll but was not handled in user code
Additional information: Items collection must be empty before using ItemsSource.
我不明白我怎麼能傳遞faceImages類我的列表視圖元素。
你必須ListView.Items東西(所以例如,你手動添加一些項目在XAML ListView控件或以某種方式加入代碼之前的東西項目集合),所以你不能使用的ItemsSource,因爲Items和ItemsSource是互斥的。 – Evk
@Evk我想爲這種情況找到一些解決方案,如有必要,我可以重寫所有內容。 – goGud
也應該使用ObservableCollection而不是列表作爲itemSource或綁定不會更新 – MikeT