-1

I'm running in to a seemingly simple problem, but can't seem to get around it >_<

I have a comboBox populated with myCustomObjects (programmatically). When I click on a button, I want to grabbed the currently selected myCustomObject and put it in another list. How do I go about doing this? myComboBox.SelectedItem returns a comboBoxItem instead of a myCustomObject.

H.B.
  • 166,899
  • 29
  • 327
  • 400
Ace
  • 821
  • 3
  • 16
  • 37

3 Answers3

2

The SelectedItem property returns the entire object that your list is bound to. It returns an object and you can cast it to your own type.

if (myComboBox.SelectedItem is MyObjectType)
{
   MyObjectType myObj =  (MyObjectType)myComboBox.SelectedItem;
}

EDIT

If you populate items programmatically you either have to tag the actual object to the ComboBoxItem.Tag property or get the myComboBox.SelectedValue and find the corresponding item from your item list.

Hope this is something worth to look at for you : Difference between SelectedItem, SelectedValue and SelectedValuePath

Community
  • 1
  • 1
CharithJ
  • 46,289
  • 20
  • 116
  • 131
  • if SelectedItem returns a ComboBoxItem do you think MyObjectType inherits that and cast will work? – Valentin Kuzub Sep 13 '11 at 03:58
  • well if it returns ComboBoxItem it means values are stored inside them somewhere, if display results satisfy the task . Also there is no binding I suspect since "combobox is populated programatically" – Valentin Kuzub Sep 13 '11 at 04:03
1

Your ComboBox.SelectedItem binds to a ComboBoxItem because you probably didn't set the ComboBox.ItemsSource to your collection of objects. Instead I think you add your objects manually as ComboBoxItems. If you bind the ItemsSource to your collection then SelectedItem will return your object.

Dummy01
  • 1,985
  • 1
  • 16
  • 21
  • No, I am answering the same question. I just try to explain him more on how the SelectedItem will have the correct object. Aren't you have something more important to do than being offensive without a reason? No one is going to steal your points!!! – Dummy01 Sep 14 '11 at 08:21
0

ComboBoxItem.Tag or ComboBoxItem.Content should hold desired value. you can also check whether ComboBox.SelectedValue works for you

Valentin Kuzub
  • 11,703
  • 7
  • 56
  • 93
  • The hybrid of both solutions is eventually what I went with, and with a lot of casting, the Tag property worked. – Ace Sep 13 '11 at 06:07