Wpf 如何获取ListCollectionView';列表框选择的s currentItem模式=";“多重”;它';最后一个选择是什么?

Wpf 如何获取ListCollectionView';列表框选择的s currentItem模式=";“多重”;它';最后一个选择是什么?,wpf,mvvm,wpf-controls,Wpf,Mvvm,Wpf Controls,我使用MVVM和ListBox的ItemsSource绑定ListCollectionView类型 如何获取ListCollectionView的currentItem我想在SelectionMode=“Multiple”上获取ListBox的最后一个SelectedItem 当前,我可以获取第一个selectItem,它是ListCollectionView的currentItem,但无法获取最后一个SelectedItem,它是ListCollectionView的currentItem 有

我使用MVVM和ListBox的ItemsSource绑定ListCollectionView类型

如何获取ListCollectionView的currentItem我想在SelectionMode=“Multiple”上获取ListBox的最后一个SelectedItem

当前,我可以获取第一个selectItem,它是ListCollectionView的currentItem,但无法获取最后一个SelectedItem,它是ListCollectionView的currentItem

有人能帮我吗?或者告诉我一些解决办法


谢谢帮助。

您可以使用Prism的行为:

public class LastSelectionBehavior:Behavior<ListBox>
{
    private ICollectionView _itemsSource;

    protected override void OnAttached()
    {
        base.OnAttached();

        _itemsSource = AssociatedObject.ItemsSource as ICollectionView;

        if (_itemsSource != null)
            AssociatedObject.SelectionChanged += AssociatedObjectSelectionChanged;
    }

    void AssociatedObjectSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.AddedItems.Count > 0)
            _itemsSource.MoveCurrentTo(e.AddedItems[0]);
    }
}
公共类LastSelectionBehavior:Behavior
{
私有ICollectionView_itemsSource;
受保护的覆盖无效附加()
{
base.onatached();
_itemsSource=AssociatedObject.itemsSource作为ICollectionView;
如果(_itemsSource!=null)
AssociatedObject.SelectionChanged+=AssociatedObjectSelectionChanged;
}
作废关联对象SelectionChanged(对象发送者,SelectionChangedEventArgs e)
{
如果(e.AddedItems.Count>0)
_itemsSource.MoveCurrentTo(e.AddedItems[0]);
}
}
Xaml:


thaks Bill Zhang。我更改了“AssociatedObjectSelectionChanged”方法,然后它就可以工作了,但是当SelectionMode=“Extended”时,您会建议为currentItem获取LastItem吗?谢谢。如果SelectionMode =“扩展”,你必须考虑方向。使用Ctrl键时,两个方向都可以,因为AddedItems只包含一个元素。但是,当使用shift时,应该考虑选择是上还是下。如果选择向上,则应将当前移动到e.AddedItems[0],否则应将当前移动到e.AddedItems[e.AddedItems.Count-1]。要确定是向上还是向下,请首先获取AssociatedObject的索引,即e.AddedItems的索引[0]。若第一个指数小于第二个,则为下跌,否则为上升。精辟的分析,使我受益匪浅。
    <ListBox ItemsSource="{Binding Path=NamesView}" SelectionMode="Multiple">
        <i:Interaction.Behaviors>
            <local:LastSelectionBehavior/>
        </i:Interaction.Behaviors>
    </ListBox>