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

发布于 2024-09-12 11:54:25 字数 572 浏览 1 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

留蓝 2024-09-19 11:54:25

您尝试过 MyComboBox.Text 吗?这将返回当前所选项目的文本。

您还可以将 SelectItem 解析为您设置的数据源的类型,并直接从对象中获取您想要的文本属性?

IE

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

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

MyObject obj = (MyObject)MyComboBox.SelectedItem;
string text = obj.Text;
贪恋 2024-09-19 11:54:25

每个项目都是一个对象。
显示的数据是 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文