Check if item exists in ListView
Solution 1
If you just want if the name has allready been added you can use linq like this
if(!listView2.Items.Any(item => item.Name == theNameToCheck))
{
//copy item
}
Contains()
would require you to have have IEquatable
Implemented by the class of the ListViews
items:
class Test : IEquatable<Test>
{
public string Name { get; set; }
public int OtherProperty { get; set; }
public bool Equals(Test other)
{
return other.Name == this.Name;
}
}
Then you can just do:
if(!listView2.Items.Contains(theItem))
{
listView2.Items.Add(theItem);
}
That is unless you really have the same instance of the class and not a copy of the class (another object with the same properties)
Solution 2
Assuming that you just give a simple list to the listviews:
listView1.Items = myItemList;
and you use the same list to copy the elements to the second listview, you could simply do this:
MyItem itemToCopy = listView1.SelectedItem; //Or where ever your item comes from
if(!listView2.Items.contains(itemToCopy)
{
listView2.Items.add(itemToCopy);
}
else
{
// Item is already in the list
}
Tal
Updated on June 04, 2022Comments
-
Tal almost 2 years
I have this code:
<Page.Resources> <DataTemplate x:Key="IconTextDataTemplate"> <StackPanel Orientation="Horizontal" Width="220" Height="60" Background="#FF729FD4"> <Border Background="#66727272" Width="40" Height="40" Margin="10"> <Image Source="/SampleImage.png" Height="32" Width="32" Stretch="UniformToFill"/> </Border> <StackPanel Orientation="Vertical" VerticalAlignment="Center"> <TextBlock Text="{Binding Name}" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis"/> <TextBlock Text="{Binding Description}" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis"/> </StackPanel> </StackPanel> </DataTemplate> </Page.Resources> <ListView x:Name="Name" ItemTemplate="{StaticResource IconTextDataTemplate}" Grid.Row="6" Margin="40,20,40,10" HorizontalAlignment="Stretch" Foreground="White" SelectionChanged="DoSomething"> <ListView.ItemsPanel> <ItemsPanelTemplate> <ItemsWrapGrid MaximumRowsOrColumns="4"/> </ItemsPanelTemplate> </ListView.ItemsPanel> </ListView>
And another
ListView
with the same properties with anotherx:Name
. I need to copy the items from oneListView
to another.I have a code that do it, my question is how can I check if the item in one
ListView
already copied to the secondListView
? Thanks.