Benson Lan
Benson Lan

Reputation: 13

How get ListCollectionView's currentItem for ListBox SelectionMode="Multiple" it's the last selectedItem?

I using MVVM,and ListBox' ItemsSource Binding ListCollectionView Type.

How get currentItem for ListCollectionView that I wanna get ListBox's the Last SelectedItem on SelectionMode="Multiple"

Currently,I can get first selectItem that be ListCollectionView's currentItem ,but cant get the last SelectedItem be ListCollectionView's currentItem.

Can anyone help me? or tell me some solutions.

thanks helpe.

Upvotes: 0

Views: 560

Answers (1)

Bill Zhang
Bill Zhang

Reputation: 1939

You can use Prism's Behavior:

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]);
    }
}

Xaml:

    <ListBox ItemsSource="{Binding Path=NamesView}" SelectionMode="Multiple">
        <i:Interaction.Behaviors>
            <local:LastSelectionBehavior/>
        </i:Interaction.Behaviors>
    </ListBox>

Upvotes: 1

Related Questions