简体   繁体   English

WPF C#-ComboBox方法返回对象而不是字符串

[英]WPF C# - ComboBox methods return object instead of string

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. 我是WPF的新手,我试图找出如何在ComboBox中获取所选项目的当前文本值。 I saw in this question someone suggested doing MyComboBox.SelectedItem.Text . 我在这个问题中看到有人建议做MyComboBox.SelectedItem.Text However, SelectedItem returns object for me, so I only have options like ToString() , Equals , etc. What's going on? 但是, SelectedItem为我返回了object ,因此我只有ToString()Equals等选项。这是怎么回事? 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 . 我使用的是在VS 2010中开发的.NET 3.5。我认为可能有用的其他方法,例如MyComboBox.SelectedValue ,也返回object SelectedIndex returns int , but I want a string value. SelectedIndex返回int ,但是我想要一个string值。 MyComboBox is of type ComboBox . MyComboBox的类型为ComboBox I'm accessing it in a method to handle the SelectionChanged event. 我正在使用一种方法来处理SelectionChanged事件。

Have you tried MyComboBox.Text ? 您是否尝试过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? 您还可以将SelectItem解析为已设置的数据源的类型,并直接从对象中获取所需的text属性?

ie

MyObject obj = (MyObject)MyComboBox.SelectedItem;
string text = obj.Text;

Each Item is a Object. 每个项目都是一个对象。 The Displayed Data is Object.ToString (Item.ToString) 显示的数据是Object.ToString(Item.ToString)

But you can Use any other Object member, Property or method from Object. 但是您可以使用Object中的任何其他Object成员,Property或Method。 You have added the object to Combo, then you know Object Type and can Cast it. 您已将对象添加到Combo,然后知道对象类型并可以进行转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM