检查项目是否存在于ListView中 [英] Check if item exists in ListView
问题描述
我有此代码:
<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>
和另一个ListView
具有与另一个x:Name
相同的属性.我需要将项目从一个ListView
复制到另一个.
And another ListView
with the same properties with another x:Name
. I need to copy the items from one ListView
to another.
我有执行此操作的代码,我的问题是如何检查一个ListView
中的项目是否已复制到第二个ListView
?
谢谢.
I have a code that do it, my question is how can I check if the item in one ListView
already copied to the second ListView
?
Thanks.
推荐答案
如果只想添加名称,则可以使用linq这样的方式
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()
将要求您具有由ListViews
项的类实现的IEquatable
:
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;
}
}
然后您可以做:
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)
这篇关于检查项目是否存在于ListView中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!