Binding the SelectedItem list to an observable collection?

I have a Listbox in WPF with SelectionMode set to Multiple and you can select items multiple times in the Listbox. However, the SelectedItem does not update the Observable Collection it is bound to.

Is there a way to bind multiple selected items from a ListBox to an observable collection?

+2


a source to share


1 answer


I do not know how to do this mvvm, I have a working solution, comimined mvvm and 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>

      

+1


a source







All Articles