Ivan
Ivan

Reputation: 1171

How to add list entries to a ListView in WPF?

I am trying to add items of list of images to ListView in WPF like this:

CS

for (int i = 0; i < filtered_thumbnails.Count; i++)
{ 
    Image tmp = new Image();
    tmp = filtered_thumbnails.ElementAt(i);
    filtered_thumbnails.RemoveAt(i);  
    SlideTransitionsList.Items.Add(tmp);                    
}

Xaml

<ListView Background ="LightGray" Name="SlideTransitionsList" Grid.Row="10" Grid.Column="1" Grid.ColumnSpan="8" Grid.RowSpan="25" SelectionChanged="SlideTransitionsList_SelectionChanged" ItemsSource="{Binding}">
    <ListView.ItemsPanel>
          <ItemsPanelTemplate>
               <UniformGrid Columns="1"/>
          </ItemsPanelTemplate>
   </ListView.ItemsPanel>

</ListView>

But I keep getting an error saying that it can't add elements because they are already child elements of other parent. So I tried to remove the item from the list prior to adding it to the ListView, but it still gives the same error. Can somebody help me please?

Upvotes: 0

Views: 132

Answers (2)

Basti
Basti

Reputation: 1004

if you are using the databinding described in the other solution change your code to.

Otherwise omit the ItemsSource={Binding} of the following example

<ListView Background ="LightGray" Name="SlideTransitionsList" Grid.Row="10" Grid.Column="1" Grid.ColumnSpan="8" Grid.RowSpan="25" SelectionChanged="SlideTransitionsList_SelectionChanged" ItemsSource="{Binding}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding}" Stretch="Uniform"></Image>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29036

why can't you bind the filtered_thumbnails list like the following :

SlideTransitionsList.ItemsSource=filtered_thumbnails;

If you iterate the filtered_thumbnails and assign each element seperately, during the first iteration the the image source is assigned to the collection, so in the second iteration, the item source is not empty(it having the first assigned element) so it doesn't allow to change. but you can assign a List as ItemSource to a list as mentioned above.

In your updates ListView defenition is missing, so i suggest you to define Like the following:

<ListView name="filtered_thumbnails" ItemsSource="{Binding}">
    <ListView .ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding}" Stretch="Uniform"></Image>
        </DataTemplate>
    </ListView .ItemTemplate>
</ListView>

Upvotes: 3

Related Questions