2010-02-27 76 views
6

这可能是C#101所涵盖的东西,但我一直无法在谷歌或堆栈溢出的任何地方找到一个易于理解的问题的答案。有没有更好的方式来从组合框返回文本值,而不使用这个糟糕的工作,我想出了?如何从WPF中的ComboBox获取文本值?

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。

回答

11

它看起来像你ComboBox中的ComboBoxItems,所以SelectedValue返回一个ComboBoxItem和ToString因此返回类似ComboBox SomeValue

如果是这样的话,你可以使用ComboBoxItem.Content获取内容:

ComboBoxItem selectedItem = (ComboBoxItem)(test_site.SelectedValue); 
string value = (string)(selectedItem.Content); 

然而,更好的办法是,而不是与ComboBoxItems集合填充组合框,以ComboBox.ItemsSource设为所需的字符串集合:

test_site.ItemsSource = new string[] { "Alice", "Bob", "Carol" }; 

然后,SelectedItem将直接为您提供当前选定的字符串。

string selectedItem = (string)(test_site.SelectedItem); 
+0

通过异常的第一个建议:无法强制类型为'System.Windows.Controls.ListBoxItem'的对象类型为'System.Windows.Controls.ComboBoxItem'。 – Akers 2010-02-27 19:44:56

+1

第二个建议很好用!谢谢一堆! – Akers 2010-02-27 19:48:17

1

在加载事件把

DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(ComboBox.TextProperty, typeof(ComboBox)); 

dpd.AddValueChanged(cmbChungChi, OnTextChanged); 

,并通过funtion

private void OnTextChanged(object sender, EventArgs args) 
{ 
    txtName.Text = cmbChungChi.Text; 
} 

造化弄文。

相关问题