【发布时间】:2019-11-07 15:58:31
【问题描述】:
我有以下视图模型类:
public class ViewModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private bool _isSelected;
public bool IsSelected {
get => _isSelected;
set {
if (value == _isSelected) { return; }
_isSelected = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsSelected)));
}
}
public int Data { get; }
public ViewModel(int data) => Data = data;
}
还有以下观点:
<Window x:Class="MVVMScrollIntoView.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DataGrid Name="dg">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</DataGrid.RowStyle>
</DataGrid>
</Window>
我在代码隐藏中设置DataGrid的ItemsSource如下:
var data = Enumerable.Range(1, 100).Select(x => new ViewModel(x)).ToList();
dg.ItemsSource = data;
在数据网格中选择/取消选择行被传播到视图模型实例,并且从代码到视图模型的IsSelected 属性的更改被传播回数据网格。
但我希望当 IsSelected 属性通过视图模型中的代码设置时:
data[79].IsSelected = true;
选定的数据网格行也应该滚动到视图中,大概是使用数据网格的ScrollIntoView 方法。
我最初的想法是在视图代码隐藏中监听 SelectionChanged 事件:
dg.SelectionChanged += (s, e) => dg.ScrollIntoView(dg.SelectedItem);
但这不起作用,因为SelectionChanged 仅在虚拟化开启时在可见项目上触发。
关闭虚拟化是一种成功的解决方法:
<DataGrid Name="dg" EnableRowVirtualization="False">
...
但我担心大型列表(20K+ 项)对性能的影响,所以我不想这样做。
执行此操作的 MVVM 方式是什么?
【问题讨论】: