这可能是C#101所涵盖的内容,但我无法在谷歌或堆栈溢出的任何地方找到这个问题的易于理解的答案.有没有更好的方法从组合框中返回文本值而不使用我想出的这种糟糕的工作?
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]);
}
Run Code Online (Sandbox Code Playgroud)
请不要狠狠地对我说话,我现在真的只是拿起c#和OOP.
ito*_*son 14
看起来你的ComboBox中有ComboBoxItems,因此SelectedValue返回一个ComboBoxItem,因此ToString返回类似的东西ComboBox SomeValue.
如果是这种情况,您可以使用ComboBoxItem.Content获取内容:
ComboBoxItem selectedItem = (ComboBoxItem)(test_site.SelectedValue);
string value = (string)(selectedItem.Content);
Run Code Online (Sandbox Code Playgroud)
但是,更好的方法是将ComboBox.ItemsSource设置为所需的字符串集合,而不是使用ComboBoxItems的集合填充ComboBox:
test_site.ItemsSource = new string[] { "Alice", "Bob", "Carol" };
Run Code Online (Sandbox Code Playgroud)
然后SelectedItem将直接为您提供当前选定的字符串.
string selectedItem = (string)(test_site.SelectedItem);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9589 次 |
| 最近记录: |