I have a WPF ComboBox:
<ComboBox ... ItemsSource="{Binding Source={StaticResource viewModel}, Path=getItems, Mode=OneTime}" x:Name="combobox" SelectionChanged="combobox_SelectionChanged">
...
</ComboBox>
with lots of items.
And my ViewModel class:
public class ViewModel
{
private readonly ObservableCollection<ObjectA> _objectACollection= new ObservableCollection<ObjectA>();
public ViewModel()
{
_objectACollection.Add(new ObjectA("Text 1", "Text", "Text"));
_objectACollection.Add(new ObjectA("Text 2", "Text", "Text"));
_objectACollection.Add(new ObjectA("Text 3", "Text", "Text"));
}
public void combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Trace.WriteLine(combobox.SelectedIndex);
}
public ObservableCollection<ObjectA> getItems
{
get { return _objectACollection; }
}
}
and the selectionChanged listener:
private void combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Trace.WriteLine(combobox.SelectedIndex);
}
The ComboBox is displayed and when I choose something I get the index of the collection objects.
But is there any way to return me the object? for example:
I select the first element in the ComboBox(index 0),
how can I get (in the combobox_SelectionChanged listener) the object from the _objectACollection with index 0?
There is SelectedItem property of ComboBox. I think that you can bind SelectedItem with TwoWay with your VM. Following is exmaple. I hope that this help.
You should add SelectedObjectA property in your VM. You can get selected item from VM.SelectedObjectA property.