0

I have ObservableCollection from class named A. (ObservableCollection<A>). This collection (lets call it listA) is binded to ListBox (lets call it itemsList). This ListBox has SelectionMode=Extended, so I want to be able to select multiple items. I'm trying to get the selected items of that itemsList. The problem is that the SelectedItems returns list of objects, and I dont know how to "convert" it to ObservableCollection from class A. I need to put it in the xml, for instance, if I have a TextBox binded to string in class A. Example:

<TextBox Text={Binding ElementName=itemsList, Path=SelectedItems.stringA}"/>

And of course that I have the DataContext to that TextBox

Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
amirm
  • 41
  • 1
  • 11

2 Answers2

1

Just use this binding:

<TextBox 
    x:Name="MyTextBox"
    TextChanged="TextBoxBase_OnTextChanged"
    Text="{Binding Path=SelectedItems[0].Content, 
    ElementName=MyListBox,
    NotifyOnSourceUpdated=True, 
    UpdateSourceTrigger=PropertyChanged,
    Mode=TwoWay}">
</TextBox>

You will need TextBoxBase_OnTextChanged event handler, which will look like this:

private void TextBoxBase_OnTextChanged(object sender, TextChangedEventArgs e)
{
    MyListBox.SelectedItems.Cast<A>().ToList().ForEach(x => x.Content = MyTextBox.Text);
}
Erti-Chris Eelmaa
  • 25,338
  • 6
  • 61
  • 78
0

If you want to show StringA from the first selected item, you can try with binding to index in collection. Something like this:

<TextBox Text={Binding ElementName=itemsList, Path=SelectedItems[0].stringA}"/>
Jurica Smircic
  • 6,117
  • 2
  • 22
  • 27
  • Tried it. It works with single selection but when selecting multiple items and editing the textbox, only the first item changed, while I wanted also all the other selecteditems.stringA to be the same as the first selecteditem.stringA – amirm Dec 22 '13 at 19:29
  • Well thats a different and more complicated story.I don't think you can solve that with some simple Binding. You will need some more logic, maybe another object that knows the value in the textbox and what items are selected. If you have that then you can update the property in all the selected items. – Jurica Smircic Dec 22 '13 at 19:44