具有自下而上连续选择的 WPF DataGrid

WPF DataGrid with continuous selection from the bottom up

如何制作一个只支持从下往上连续范围选择的DataGrid?用户单击一个项目,只有这个和它下面的项目应该被选中。我有一个带有 IsSelected-属性 的 ViewModel,我像这样绑定到 RowStyle:

<DataGrid.RowStyle>
  <Style TargetType="{x:Type DataGridRow}" BasedOn="{StaticResource {x:Type DataGridRow}}">
    <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
  </Style>
</DataGrid.RowStyle>

但是我尝试这样做时,我得到了一些奇怪的行为,这些行为似乎与 WPF 在 DataGrids 内部处理选择的方式相冲突。我似乎无法像我想要的那样完成这项工作。有什么建议吗?

我现在执行选择逻辑的方式是,当绑定的 IsSelected-属性 由 WPF 更新时,我有一个 "selection manager" 启动,然后选择多个项目,特别是所有以下项目,包括。但是,例如,当用户单击一个已选中的项目时,我根本没有收到任何事件(有时),这可能是因为 WPF 认为不需要这样做,因为 属性 已被选中。而且还有更多的问题。试着思考如何绕过所有这些内部逻辑而不把它弄得一团糟。我仍然希望行上的正常选择外观。

我不确定你的视图模型是如何构建的,但我会这样做:

在您的视图模型中创建一个 SelectedItems 属性 以及一个 UpdateSelectionCommand。 GridView.SelectemItems 绑定到 VM.SelectedItems

    private IList<SelectedItemViewModel> _SelectedItems;

    public IList<SelectedItemViewModel> SelectedItems
    {
        get
        {
            if (_SelectedItems == null)
            {
                //populate selected items; 
            }
            return _SelectedItems;
        }
        private set
        {
            //set _selected items to null here. 
            //FirePropertyChanged(): forces repopulation of _SelectedItems based on the new selection
        }
    }

    public ICommand UpdateSelectionCommand
    {
        get
        {
            return new RelayCommand(_ => SelectedItems = null, true));
        }
    }

UpdateSelectionCommand 由鼠标左键单击(MouseUp 事件)触发 - 这应该可以解决项目已被选中并且重新选择它不会触发更改的问题。