获取仅包含文本条目的组合框的选定文本的最简单方法是什么? [英] What is the simplest way to get the selected text of a combo box containing only text entries?
问题描述
我的WPF组合框仅包含文本条目.用户将选择一个. 获取所选ComboBoxItem文本的最简单方法是什么?请同时使用C#和Visual Basic进行回答.这是我的组合框:
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>
顺便说一句,我知道答案,但要找到它并不容易.我以为我会发布问题来帮助他人.修订:我学会了一个更好的答案.通过将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屋!