XSL
XSL

Reputation: 3055

LongListSelector get selected index

Is there a way to get the index of a particular element from a LongListSelector control? I'd like to remove the object the user has selected but there doesn't seem to be a straightforward way of doing this. The LongListSelector's data source (ObservableCollection) can contain duplicates so if I call remove on it then it would only remove the first instance it comes across instead of the one the user selected.

I can use the ObservableCollection's RemoveAt method but I can't seem to get the index from the LongListSelector so that I can pass it as the parameter for the RemoveAt method.

Upvotes: 0

Views: 864

Answers (1)

Mats Lannér
Mats Lannér

Reputation: 1356

Not sure if this will help you or not, but if you use an overall MVVM approach in your app, you'd typically have a view model for each item in the list. With that you can define an IsSelected property on the item view model and data-bind that to the LongListSelector control. Then when you need to delete items you just find all items with IsSelected set to true.

As a simple example, in one of my item view models I have this property:

    /// <summary>
    /// Is this location selected in the UI?
    /// </summary>
    public bool Selected
    {
        get { return _selected; }
        set
        {
            if ( value != _selected )
            {
                _selected = value;
                RaisePropertyChanged( "Selected" );
            }
        }
    }

Then in my XAML item template I have a check box control bound like this:

<CheckBox Grid.Column="0" Grid.RowSpan="2" IsChecked="{Binding Path=Selected,Mode=TwoWay}"
          VerticalAlignment="Top" Margin="0,-10,0,0"/>

Hope this helps.

Upvotes: 2

Related Questions