开发者

Listview selecting muliple indexes

开发者 https://www.devze.com 2023-03-09 05:44 出处:网络
For a ListView where I can select multiple items from the list, my method for the selected Index will be called if I\'m selecting one item. But I I select more than one at a time my \'TheSelectedIndex

For a ListView where I can select multiple items from the list, my method for the selected Index will be called if I'm selecting one item. But I I select more than one at a time my 'TheSelectedIndex' method is not being called. I want it to be called for any type of selection. zero items, 1 item ore more than 1 item. How do I set it up for that? Thank you very 开发者_运维知识库much!

<ListView
           SelectionMode="Multiple"
           SelectedIndex="{Binding Path="TheSelectedIndex}"
           ItemsSource="{Binding Path=Object}">


One way to handle this is to ensure that the type to which you bind the ItemsSource property exposes an IsSelected property. This may mean wrapping that type into a custom ViewModel class that simply exposes the underlying type and adds an IsSelected property.

Once you introduce the concept of selection state to the individual items in the bound collection, you can leverage the ListView.SelectionChanged event and some code-behind to access the view-model (assumes you're using MVVM, which I think you are, considering your bindings):

In XAML...

<ListView SelectionChanged="ListView_SelectionChanged" />

In code-behind...

private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var vm = (MyViewModel)DataContext;
    var selectedItems = ((ListView)sender).SelectedItems.Cast<SomeType>();        

    vm.SetSelectedItems(selectedItems);
}

In view-model...

public void SetSelectedItems(IEnumerable<SomeType> selectedItems)
{
    /* Remove items that were previously selected but no longer are selected */
    var currentlySelectedItems = MyItems.Where(i => i.IsSelected == true);
    foreach (var previouslySelectedItem in currentlySelectedItems.Except(selectedItems))
        previouslySelectedItem.IsSelected = false;

    /* Set the selection state on all currently/newly selected items */
    foreach (var selectedItem in selectedItems)
        selectedItem.IsSelected = true;

    NotifyOfPropertyChanged(() => MyItems);
}

In SomeType, which is a view-model wrapper for each item in the collection...

public bool IsSelected { get; set; }


You have to use SelectionChanged event

0

精彩评论

暂无评论...
验证码 换一张
取 消