There is a ListBox and TextBox , the first one is bound to ObservableCollection<Adress> , where Adress is

 public struct Adress { public Adress(string text, double x, double y) { Text = text; X = x; Y = y; } public string Text { get; set; }//Именно это свойство отображается в "ListboxItem" public double X { get; set; } public double Y { get; set; } } 

TextBox bound to a property-string, in the setter of which I tried to filter, but all is in vain. I tried ICollectionView with the help of ICollectionView , but did not figure out how to achieve the desired result.

And now about what the desired result is - when entering text into a TextBox , those elements in ListBox 'e that contain this text (regardless of case) - remain visible, and the rest are “hidden” (I think just to use Visibility.Collapsed , but here all means will be good). Here I can not understand how to implement it without violating the principles of MVVM.

    1 answer 1

    As a result, I figured it out myself, my own inattention was to blame for everything - I didn’t correctly specify Binding for TextBox :

     <TextBox Text="{Binding AdressFilterText}"/> 

    Thus, the following code is fully operational:

     <TextBox Text="{Binding AdressFilterText, UpdateSourceTrigger=PropertyChanged}"/> <ListBox ItemsSource="{Binding Adresses}"/> 

    And C #:

     public ObservableCollection<Adress> Adresses { get; set; } private ICollectionView _adressFilter = CollectionViewSource.GetDefaultView(Adresses); public string AdressFilterText { get => _adressFilterText; set { if(value != _adressFilterText) { _adressFilterText = value; OnPropertyChanged("AdressFilterText"); } _adressFilter.Filter = o => { if (((Adress)o).Text.ToLower().Contains(value.ToLower())) return true; else return false; }; } } private string _adressFilterText; 
    • In my opinion, ICollectionView should be in View if you follow MVVM classics - user227049
    • @FoggyFinder, and how will the ViewModel know about it if it is in View ? Or did I somehow misunderstand? - Arthur Edgarov
    • No way, if filtering is used only for presentation, then the VM does not need to be aware of what is currently displayed to the user - user227049
    • @FoggyFinder, hmm, you are probably right. And then filter using Behavior ? - Arthur Edgarov
    • You can filter through and ICollectionView at the View level, if you understand correctly. MVVM does not mean rejection of code-behind - user227049