滚动到选定项的 WPF 当 PropertyChanged 事件被触发时。

huangapple go评论99阅读模式
英文:

Scroll to SelectedItem WPF when the PropertyChanged event is raised

问题

我使用WPF与MVVM。

我的XAML视图包含一个绑定到ICollectionView的ListView。在我的ViewModel中,我处理OnPropertyChange事件以选择该特定的ListView项当它的属性发生更改时。然后,我从视图的代码后台滚动到它。

问题是滚动与XAML中的Selection_Changed绑定在一起,因此如果已选择具有更改属性的项目,则不会滚动到它。

如果项目已经被选择,我如何实现滚动?

英文:

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?

答案1

得分: 0

代替处理SelectionChanged事件,你可以例如处理与定义了被设置的属性的视图模型类的PropertyChanged事件,例如:

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))
        {
            // 滚动...
        }
    }
}
英文:

>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...
        }
    }
}

huangapple
  • 本文由 发表于 2023年6月5日 22:37:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76407543.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定