[英]How do i get the text value from a ComboBox in WPF?
這可能是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]);
}
請不要狠狠地對我說話,我現在真的只是拿起c#和OOP。
看起來你的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);
在加載事件放
DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(ComboBox.TextProperty, typeof(ComboBox));
dpd.AddValueChanged(cmbChungChi, OnTextChanged);
並通過功能獲取文本
private void OnTextChanged(object sender, EventArgs args)
{
txtName.Text = cmbChungChi.Text;
}
祝好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.