Bài viết phổ biến của tác giả
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
这可能是 C# 101 中涵盖的内容,但我无法在 google 或 stack overflow 上的任何地方找到该问题的易于理解的答案。有没有更好的方法来从组合框返回文本值,而无需使用我想出的这种糟糕的解决方法?
private void test_site_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string cmbvalue = "";
cmbvalue = this.test_site.SelectedValue.ToString();
string[] cmbvalues = cmbvalue.Split(new char[] { ' ' });
MessageBox.Show(cmbvalues[1]);
}
请不要责备我,我真的只是刚刚开始学习 C# 和 OOP。
câu trả lời hay nhất
看起来您的 ComboBox 中有 ComboBoxItems,因此 SelectedValue 返回 ComboBoxItem,因此 ToString 返回类似 ComboBox SomeValue
的内容。
如果是这种情况,您可以使用 ComboBoxItem.Content 获取内容:
ComboBoxItem selectedItem = (ComboBoxItem)(test_site.SelectedValue);
string value = (string)(selectedItem.Content);
但是,更好的方法是将 ComboBox.ItemsSource 设置为所需的字符串集合,而不是使用 ComboBoxItems 集合填充 ComboBox:
test_site.ItemsSource = new string[] { "Alice", "Bob", "Carol" };
然后 SelectedItem 将直接为您获取当前选择的字符串。
string selectedItem = (string)(test_site.SelectedItem);
关于c# - 我如何从 WPF 中的 ComboBox 获取文本值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2348646/
Tôi là một lập trình viên xuất sắc, rất giỏi!