Search code examples
c#wpfmvvm

Scroll to SelectedItem WPF when the PropertyChanged event is raised


Im using WPF with MVVM.

My XAML view contains a listview bound to an ICollectionView. In my viewModel I handle an OnPropertyChange event to select that particular list view item when it's property changes. Then, I scroll to in from the view code behind.

The problem is the scroll is bound to Selection_Changed in the xaml so if the item that had its property changed is already selected it will not scroll to it.

How do I achieve the scrolling if the item is already selected?


Solution

  • How do I achieve the scrolling if the item is already selected?

    Instead of handling the SelectionChanged event, you could for example handle the PropertyChanged event for the view model class where the property that is set is defined, e.g.:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
    
            var viewModel = new ViewModel();
            DataContext = viewModel;
    
            viewModel.PropertyChanged += OnViewModelPropertyChanged;
    
            ...
        }
    
        private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(ViewModel.SelectedItem))
            {
                // scroll...
            }
        }
    }