英文:
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...
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论