There is a listview . He zabaydin with ObservableCollection<MyObject> . Is it possible to organize a search "on the fly" in the collection with the selection found? Those. There is a TextBox with a trigger EventName="TextChanged" and when entering characters there, in the listview display the appropriate entries. Found such an option, but I need MVVM.

    1 answer 1

    The task is solved easily, except for Binding nothing is required.
    Markup:

     <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition/> </Grid.RowDefinitions> <TextBox Text="{Binding Pattern, UpdateSourceTrigger=PropertyChanged}" Margin="5,5,5,0" Padding="3"/> <ListBox Grid.Row="1" Margin="5" ItemsSource="{Binding Strings}" SelectedItem="{Binding Selected}"/> </Grid> 

    ViewModel:

     class MainVM : INotifyPropertyChanged { string _pattern; public string Pattern { get => _pattern; set { Set(ref _pattern, value); Selected = Strings.FirstOrDefault(s => s.StartsWith(Pattern)); } } string _selected; public string Selected { get => _selected; set => Set(ref _selected, value); } public ObservableCollection<string> Strings { get; } public MainVM() { Strings = new ObservableCollection<string> { "Телевизор", "Телефон", "Кровать", "Чемодан", "Стол", "Шкаф", "Чайник" }; } protected void Set<T>(ref T field, T value, [CallerMemberName] string propertyName = "") { field = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; } 

    enter image description here


    Add a scroll to the selected Item.
    Subscribe to the event in the markup:

     <ListBox Grid.Row="1" Margin="5" ItemsSource="{Binding Strings}" SelectedItem="{Binding Selected}" SelectionChanged="OnSelectionChanged"/> 

    Event handler in MainWindow.xaml.cs :

     private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { var listBox = sender as ListBox; listBox.ScrollIntoView(listBox.SelectedItem); } 

    enter image description here

    • There may be a small problem: when there are quite a lot of items in the list, you still need to implement scrolling to the selected item in some way, it will not automatically be scrolled to the selected item. - Bulson
    • one
      @Bulson presentation Subscribe to SelectionChanged and scroll to the selected one. VM does not need to think about it. - Andrei NOP
    • Shine, thank you! And according to SelectionChanged, is it like a trigger to hang and scroll in the LV itself? Or through the team? - Rans
    • one
      @Rans, supplemented the answer - Andrey NOP