Silverlight - 如何在组合框中获取所选项目的文本

问题描述:

很容易为你所有...

Easy one for you all...

我是Silverlight的新人,真的缺少像DataTables和东西的东西。我目前还在努力是如何获取我的组合框的当前选择的项目的文本。
在winforms中我会做:

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.

组合框的选定项目是当前持有的任何类型的项目。因此,如果您将绑定设置为字符串集合,则所选项将是一个字符串:

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);

如果它是一个更复杂的对象,你需要转换和使用期望的对象。如果你有XAML使用列表框项目类,如:

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;