在仅包含文本条目的组合框中获取所选文本的最简单的方法是什么? [英] What is the simplest way to get the selected text in a combo box containing only text entries?
问题描述
我的WPF ComboBox只包含文本条目。用户将选择一个。 获取所选ComboBoxItem文本的最简单方法是什么?请在C#和Visual Basic中回答。这是我的ComboBox:
My WPF ComboBox contains only text entries. The user will select one. What is the simplest way to get the text of the selected ComboBoxItem? Please answer in both C# and Visual Basic. Here is my ComboBox:
<ComboBox Name="cboPickOne">
<ComboBoxItem>This</ComboBoxItem>
<ComboBoxItem>should be</ComboBoxItem>
<ComboBoxItem>easier!</ComboBoxItem>
</ComboBox>
顺便问一下,我知道答案,但不容易找到。我想我会发布的问题,以帮助别人。 REVISION:我学到了一个更好的答案。通过添加SelectedValuePath =Content作为ComboBox属性,我不再需要丑陋的投射代码。
By the way, I know the answer but it wasn't easy to find. I thought I'd post the question to help others. REVISION: I've learned a better answer. By adding SelectedValuePath="Content" as a ComboBox attribute I no longer need the ugly casting code. See Andy's answer below.
推荐答案
<ComboBox
Name="cboPickOne"
SelectedValuePath="Content"
>
<ComboBoxItem>This</ComboBoxItem>
<ComboBoxItem>should be</ComboBoxItem>
<ComboBoxItem>easier!</ComboBoxItem>
</ComboBox>
在代码中:
stringValue = cboPickOne.SelectedValue.ToString()
这篇关于在仅包含文本条目的组合框中获取所选文本的最简单的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!