开发者

Binding a listbox SelectedItem to an Observable Collection?

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 multi开发者_C百科ple selected items from a ListBox to an Observable Collection?


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>

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜