Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight - how do I get the text of the selected item in a combobox

Easy one for you all...

I'm new to Silverlight and really missing stuff like DataTables and things. What I'm also currently struggling with is how to get the text of my combobox's currently selected item. In winforms I would have done:

ComboBox myCombo = new ComboBox.......
string selected = myCombo.Text;

I'm struggling how to get this info out.

like image 771
Calanus Avatar asked Dec 08 '09 17:12

Calanus


2 Answers

The selected item of your combo box is whatever type of item is currently holding. So if you set the binding to a collection of strings, then the selected item will be a string:

string mySelectedValue = ((string)MyComboBox.SelectedItem);

If it is a more complex object you will need to cast and use the expected object. If you have XAML using the list box item class, like:

<ComboBox x:Name="MyComboBox">
    <ComboBox.Items>
        <ComboBoxItem>
            <TextBlock Text="Hello World"/>
        </ComboBoxItem>
    </ComboBox.Items>
</ComboBox>

Then you would access the selected item like this:

string mySelectedValue = 
  ((TextBlock)((ComboBoxItem)MyComboBox.SelectedItem).Content).Text;
like image 73
Jason Jackson Avatar answered Oct 13 '22 00:10

Jason Jackson


Right, the answer is to use myCombo.SelectionBoxItem.ToString()

like image 36
Calanus Avatar answered Oct 13 '22 02:10

Calanus