2
votes

I have a Listbox in WPF with the SelectionMode set to Multiple, and can multiselect the items in the Listbox. However, the SelectedItem is not updating the Observable Collection it is bound to.

Is there a way to bind the multiple selected items from a ListBox to an Observable Collection?

1
possible duplicate of stackoverflow.com/questions/803216/…user1228

1 Answers

1
votes

i dont know mvvm way of doing this, i have a working solution comibined of mvvm & codebehind.

CodeBehind

private void lstbox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
    {
        var listBox = sender as ListBox;
        if (listBox == null) return;

        var viewModel = listBox.DataContext as Window1ViewModel;
        if (viewModel == null) return;

        viewModel.ListOfSelectedItems.Clear();

        foreach (Window1ViewModel.States item in listBox.SelectedItems)
        {
            viewModel.ListOfSelectedItems.Add(item);
        }
      }

ViewModel

    private ObservableCollection<States> _listofselecteditems;
    public ObservableCollection<States> ListOfSelectedItems
    {
        get
        {
            return _listofselecteditems;
        }
        set
        {
            _listofselecteditems = value;
            RaisePropertyChanged(() => ListOfSelectedItems);
        }
    }

Xaml

            <ListBox x:Name="lstbox" 
             SelectionChanged="lstbox_SelectionChanged_1"
             ItemsSource="{Binding StatesList,Mode=TwoWay}"
             SelectionMode="Multiple" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <CheckBox 
                        IsChecked="{Binding Path=IsSelected,Mode=TwoWay}"
                        Content="{Binding StateName}" />
                    <TextBox Margin="8,0,0,0" Text="{Binding SOmeProperty}" IsEnabled="{Binding Path=IsSelected}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>