2

I want when a user selects one or multiple items that my source property gets updated. I have tried with the binding mode OneWayToSource but this is not helping. Below is the XAML and ViewModel code:

<ListBox  x:Name="ItemsListBox" SelectionMode="Multiple" Height="300" 
          ItemsSource="{Binding ResultSet}"
          SelectedItem="{Binding SelectedItems,Mode=OneWayToSource}">

private List<string> _selectedItems;
public List<string> SelectedItems
{
    get
    {
        return _selectedItems;
    }
    set
    {
        _selectedModeItems = value;
        NotifyPropertyChanged("SelectedItems");
    }
}

I have taken the approach by using Attached behaviours and it works , but is there any simpler way?

Simsons
  • 12,295
  • 42
  • 153
  • 269
  • NotifyPropertyChanged("SelectedeItems"); should probably be NotifyPropertyChanged("SelectedItems"); – Abbas Mar 07 '13 at 10:31
  • Thats Just a Spelling mistake while editing the question , Updating the question. Thanks – Simsons Mar 07 '13 at 10:37

3 Answers3

1

Your question should be like this.

How to get multiple selected items from the ListBox in WPF with MVVM?

Well, you have the answer from following stackoverflow threads.

link 1

link 2

Simply you can define IsSelected property in your ResultSet view model. Then if you want to get selected items at any point, just get the items which the "IsSelected" property is set to true from the ResultSet.

Community
  • 1
  • 1
Haritha
  • 1,498
  • 1
  • 13
  • 35
1

you could also create an Attached Behavior
here is an Example how to do it

WiiMaxx
  • 5,322
  • 8
  • 51
  • 89
0

WPF ListBox has two properties related to the currently selected item:

  • SelectedItem available for binding, bound to the first selected item.
  • SelectedItems (with an 's' at the end) is not available to binding.

When multi selection is enabled, you want to have access to SelectedItems but unfortunately you can't bind to it

You can workaround this limitation using code behind. Create a property named SelectedItems that will contain the selection, then subscribe the SelectionChanged event:

<ListBox  x:Name="ItemsListBox" SelectionMode="Multiple" Height="300" 
                          ItemsSource="{Binding ResultSet}" 
        SelectionChanged="ListBox_SelectionChanged">


private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    foreach (string item in e.RemovedItems)
    {
        SelectedItems.Remove(item);
    }

    foreach (string item in e.AddedItems)
    {
        SelectedItems.Add(item);
    }
}
sim1
  • 722
  • 7
  • 12
  • 1
    Good One , Will mark it as answer if you have used Command Binding for Selection Changed. Will update code with Binding and let's see. Code behind is not a good idea – Simsons Mar 07 '13 at 10:48