组合框/列表框所选项目

发布于 2024-08-25 14:47:53 字数 155 浏览 7 评论 0原文

有没有更简单的方法来获取组合框(WinForms)所选项目的文本?

string result = comboBox1.Items[comboBox1.Selectedindex];

那么在 WPF 的 ComboBox 中呢?

is there a more simple way to get combobox (WinForms) selected items text?

string result = comboBox1.Items[comboBox1.Selectedindex];

And in WPF's ComboBox?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

裸钻 2024-09-01 14:47:54

关于 WPF 组合框:我认为没有一个好的通用方法来获取 WPF 中所选组合框项目的文本。 wpf 组合框在模板中显示其项目,模板可以是任何内容(即嵌套在堆栈面板内、按钮内等的多个标签)。该模板甚至不需要显示任何文本,它可以显示图像或完全不同的东西。也就是说,我认为没有太多需要访问组合框中所选项目的 UI 内的文本字符串。这只是用户的 UI,程序应该与所选对象(而不是 UI 表示)进行交互。不过,可能会有一些例外,但在这种情况下,您将必须为您使用的项目模板制定特定的解决方案,因为对此没有通用的解决方案。

Regarding WPF combobox: I don't think there is a good general way of getting the text of the selected combobox item in WPF. The wpf combobox displays its items in a template, which can be anything (i.e. several labels nested inside a stackpanel, inside a button etc...). The template need not even display any text, it can for instance display an image or something completly different. That said, i don't think there is much need for accessing the text strings inside a selected item's UI in a combobox. That is just UI for the user, the program should interact with the selected object (not it's UI representation). There might be some exceptions to this, tho, but in that case, you will have to make a specific solution for the item template that you use, because there is no one-size-fits-all solution for this.

野却迷人 2024-09-01 14:47:53

string result = (string)comboBox1.SelectedItem

那这样是不是更简单呢

What about

string result = (string)comboBox1.SelectedItem

Is that more simple?

粉红×色少女 2024-09-01 14:47:53

@Zenuka的方法有效,但我认为以下内容在某种程度上“更正确”(尽可能避免强制转换):

String result = comboBox1.SelectedItem.ToString();

@Zenuka's method works but I think the following is somewhat "more correct" (avoiding casts when possible):

String result = comboBox1.SelectedItem.ToString();
沫尐诺 2024-09-01 14:47:53

不,抱歉。就是这样。

只是为了兴趣,你觉得哪一部分不简单?

nope, sorry. That's it.

Just for interest, what part of it to you thiink is not simple?

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