Daniel G
Daniel G

Reputation: 3

how to get last SelectedItem index from listview after refreshing in viewmodel using mvvm?

I can't access listview's selecteditem in viewmodel and i bound it to my CurrentProduct. How should i write the code in viewmodel so i can get the index of the CurrentProduct(selecteditem) so i after i refresh the listview i can restore the value

XAML

<ListView Name="sItem"  BorderThickness="0.4" BorderBrush="DarkGray" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding ProductList}" SelectedItem="{Binding CurrentProduct}"/>

VIEWMODEL - this is how i refresh the listview

ProductList = ProductCollection.GetAllProducts();

my viewmodel implements INotifyPropertyChanged

Upvotes: 0

Views: 935

Answers (1)

Chris Mack
Chris Mack

Reputation: 5208

You can implement a property on the ViewModel, e.g.:

private Product _productListSelectedItem;
public Product ProductListSelectedItem
{
    get { return _productListSelectedItem; }
    set
    {
        if (_productListSelectedItem != value)
        {
            _productListSelectedItem = value;
            NotifyPropertyChanged();
        }
    }
}

And then bind to this in your XAML:

<ListView Name="sItem" ... SelectedItem="{Binding ProductListSelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

When it comes to refreshing the ListView:

private void RefreshProductList()
{
    Product selectedItem = ProductListSelectedItem;

    ProductList = ProductCollection.GetAllProducts();

    if (ProductList.FirstOrDefault(p => p.ID == selectedItem.ID) != null)
    {
        ProductListSelectedItem = ProductList.First(p => p.ID == selectedItem.ID);
    }
}

Once you've refreshed the ProductList, you'll have a new set of items, so what I've done here is to store the selected item before the collection changes, and then use a LINQ expression to locate that item in the new collection via a property called ID. I'm assuming you have a property or set of properties to locate distinct items, as I think you'll need one in this case.

(I've also assumed your individual class name as Product.)

Upvotes: 1

Related Questions