Issue
public ListExercieseViewModel()
{
ListOfItemsSource = new ObservableCollection<Items>();
ListOfItemsSource.Add(new Items() { MainText="First" , SecondText="Test"});
ListOfItemsSource.Add(new Items() { MainText="Second" , SecondText="Test"});
ListOfItemsSource.Add(new Items() { MainText="Third" , SecondText="Test"});
ListOfItems = ListOfItemsSource.ToList();
SearchBar = new Command(OnTextChanged);
}
public string TextChanging
{
get
{
return _TextChanging;
}
set
{
if (value != null)
_TextChanging = value;
}
}
public List<Items> ListOfItems
{
get;
set;
}
public ObservableCollection<Items> ListOfItemsSource
{
get;
set;
}
public class Items : INotifyPropertyChanged
{
public string _MainText;
public string _SecondText;
public string MainText
{
get
{
return _MainText;
}
set
{
if (value != null)
_MainText = value;
NotifyPropertyChanged();
}
}
public string SecondText
{
get => _SecondText;
set
{
if (value != null)
_SecondText = value;
NotifyPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
the problem is here:
public void OnTextChanged()
{
if (!String.IsNullOrEmpty(_TextChanging))
ListOfItems = ListOfItemsSource.Where(x => x.MainText.StartsWith(TextChanging)).ToList();
else
ListOfItems = ListOfItemsSource.ToList();
}
I try to make a filter for my elements, i use Linq to do that, but i have a problem
initially the values from ListOfItemsSource are "First", "Second", "Third", after TextChanging = "Th", count from ListOfItems are 0, but i need to filter this information to show "Third"
What is wrong
Solution
In the comments, you mention that you enter exactly "th" into the search box and expect a match with "Third". If you call string.StartsWith
without any parameters that configure the comparison, the comparison is case-sensitive. Hence "th" is no match, but "Th" would be.
The easiest way to fix this is to add a parameter that specifies that the comparison should be case-insensitive, e.g.
ListOfItems = ListOfItemsSource
.Where(x =>
x.MainText
.StartsWith(
TextChanging,
StringComparison.CurrentCultureIgnoreCase))
.ToList();
See this link for the available options.
As an alternative, you could convert the strings in the list and the text you are looking for to lowercase before comparing.
Answered By - Markus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.