如何检查项目是否已经存在于列表框中 Windows Phone 8.1 通用

How to check if item has already existed in Listbox Windows Phone 8.1 Universal

这是我的 XAML 代码:

<ListBox x:Name="MyList">
    <ListBox.ItemTemplate>
        <DataTemplate>  
            <Grid>                                             
                 <TextBlock x:Name="MyTextBlock" TextWrapping="NoWrap" 
                            Text="{Binding MyText}" />
            </Grid>  
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

谁能告诉我如何检查项目是否已经存在于列表框中? 非常感谢!

假设您使用 MyList.Items.Add("Test"); 添加了项目,您可以使用这个:

bool contained = MyList.Items.Contains("Test");

或者如果 ListBox 包含用户定义的 class 而不是字符串:

public class TestClass
{
    public string MyText { get; set; }
}

bool contained = MyList.Items.Cast<TestClass>().Any(x => x.MyText == "Test");

更好的方法是使用 MVVM 设计模式和 DataBinding