Reputation: 57
I'm trying to search a ListView to see if a certain piece of text has already been added. I've tried using other answers from here, like the code below:
ListViewItem item = ListView1.FindItemWithText(txtSearch.Text);
if (item != null)
{
// you have match
}
However, it highlights a problem with "FindItemWithText". The error message is:
'Windows.UI.Xaml.Controls.ListView' does not contain a definition for 'FindItemWithText' and no extension method 'FindItemWithText' accepting a first argument of type 'Windows.UI.Xaml.Controls.ListView' could be found (are you missing a using directive or an assembly reference?).
I'm using Visual Studio 2013 to create a Windows Phone 8.1 app.
Any help would be appreciated!
Upvotes: 2
Views: 628
Reputation: 555
How about using some LINQ
if(listView.Items.Cast<ListViewItem>().Any(c => c.Content.ToString().Contains(txtSearch.Text)))
{
// You have a match
}
Upvotes: 0
Reputation: 2675
For example you can implement an extension method which will do what you want. Consider a stupid example:
public static class ListViewExtensions {
public static object FintItemWithText(this ListView lv, string text) {
foreach (ListViewItem item in lv.Items) {
if (item.Content.ToString() == text) {
return item;
}
}
return null;
}
}
Now, you can use it like in the following example:
object result = listView.FintItemWithText("A");
I just here work with objects. It's not a good practice usually. Maybe it would be better to roll out your own class, create a list (or ObservableCollection) of it and set a binding. Than, when you know the type of items inside your ListView you can easily cast to the well known type and check it's properties as you like.
Upvotes: 1