WPF C# - ComboBox 方法返回对象而不是字符串
我是 WPF 新手,我正在尝试弄清楚如何获取组合框中所选项目的当前文本值。我在这个问题中看到有人建议这样做MyComboBox.SelectedItem.Text
。但是,SelectedItem
为我返回object
,所以我只有ToString()
、Equals
等选项。这是怎么回事?我正在使用 .NET 3.5,在 VS 2010 中进行开发。我认为可能有用的其他方法,例如 MyComboBox.SelectedValue,也返回 object。 SelectedIndex
返回 int
,但我想要一个 string
值。 MyComboBox
的类型为ComboBox
。我在处理 SelectionChanged 事件的方法中访问它。
I'm new to WPF and I'm trying to figure out how to get the current text value of the selected item in a ComboBox. I saw in this question someone suggested doing MyComboBox.SelectedItem.Text
. However, SelectedItem
returns object
for me, so I only have options like ToString()
, Equals
, etc. What's going on? I'm using .NET 3.5, developing in VS 2010. The other methods I thought might be of use, like MyComboBox.SelectedValue
, also return object
. SelectedIndex
returns int
, but I want a string
value. MyComboBox
is of type ComboBox
. I'm accessing it in a method to handle the SelectionChanged event.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您尝试过 MyComboBox.Text 吗?这将返回当前所选项目的文本。
您还可以将
SelectItem
解析为您设置的数据源的类型,并直接从对象中获取您想要的文本属性?IE
Have you tried
MyComboBox.Text
? That will return you the text of the currently selected item.You can also parse the
SelectItem
into the type of the datasource you've set it and get the text property you want directly from the object?ie
每个项目都是一个对象。
显示的数据是 Object.ToString (Item.ToString)
但您可以使用对象中的任何其他对象成员、属性或方法。
您已将对象添加到 Combo,然后您就知道对象类型并可以对其进行投射。
Each Item is a Object.
The Displayed Data is Object.ToString (Item.ToString)
But you can Use any other Object member, Property or method from Object.
You have added the object to Combo, then you know Object Type and can Cast it.