我如何获得在WPF组合框的文本值? [英] How do i get the text value from a ComboBox in WPF?
问题描述
这可能是一些覆盖在C#101,但我一直没能找到一个容易理解谷歌或堆栈溢出的任何地方这个问题的答案。有没有更好的办法返回从组合框的文本值,而不使用该蹩脚的变通,我想出了?
This may be something covered in C# 101 but I haven't been able to find an easy to understand answer to this question anywhere on google or stack overflow. Is there a better way to return a text value from a combobox without using this crappy work around I came up with?
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。
Please don't rail on me to hard I'm really just now picking up c# and OOP.
推荐答案
它看起来像你在你的组合框ComboBoxItems,这样的SelectedValue返回一个ComboBoxItem和toString是因此返回类似组合框someValue中
It looks like you have ComboBoxItems in your ComboBox, so that SelectedValue is returning a ComboBoxItem and ToString is therefore returning something like ComboBox SomeValue
.
如果是这样的话,你可以使用ComboBoxItem.Content内容:
If that's the case, you can get the content using ComboBoxItem.Content:
ComboBoxItem selectedItem = (ComboBoxItem)(test_site.SelectedValue);
string value = (string)(selectedItem.Content);
然而,更好的方法是,不再ComboBoxItems集合填充组合框,设置组合框.ItemsSource为字符串的期望系列:
However, a better approach is, instead of populating the ComboBox with a collection of ComboBoxItems, to set ComboBox.ItemsSource to the desired collection of strings:
test_site.ItemsSource = new string[] { "Alice", "Bob", "Carol" };
随后的SelectedItem会直接让你的当前选择的字符串。
Then SelectedItem will get you the currently selected string directly.
string selectedItem = (string)(test_site.SelectedItem);
这篇关于我如何获得在WPF组合框的文本值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!