2009-12-08 106 views
6

輕鬆一爲大家...Silverlight的 - 如何獲取所選項目的文本的組合框

我是新來的Silverlight和數據表一樣,事情真的錯過的東西。我目前正在努力的是如何獲得我的組合框當前選定項目的文本。 在的WinForms我會做:

ComboBox myCombo = new ComboBox....... 
string selected = myCombo.Text; 

我掙扎如何得到這個信息的。

回答

9

組合框的選擇產品的物品類型,目前持股。所以,如果你設置綁定爲字符串的集合,然後選定項目將是一個字符串:

string mySelectedValue = ((string)MyComboBox.SelectedItem); 

如果它是一個更復雜的對象,你需要轉換和使用的預期目標。如果您在使用XAML列表框中的項目類,如:用的DisplayMemberPath屬性

string mySelectedValue = 
    ((TextBlock)((ComboBoxItem)MyComboBox.SelectedItem).Content).Text; 
+0

我認爲卡拉努斯直截了當地回答問題 – Raghurocks 2012-12-20 05:43:54

+0

我的回答是3歲。我一直沒有在Silverlight中工作過一段時間,所以Calanus的答案可能適用於當前版本的Silverlight;我無法對此發表評論。當我回答時,我認爲它不適用於像這裏描述的那種豐富的組合框項目。 – 2013-01-15 17:52:01

+0

不適用於最新的silverlight。得到「無法投入」System.Windows.Controls.ComboBoxItem「類型的對象來鍵入」System.String「。」 – 2014-03-12 17:52:07

-1
myCombo.SelectedItem.Content 

將返回ComboBoxItem的內容。這可能是一個TextBlock等等,具體取決於你在那裏的內容,以及你用於項目模板的內容。

+1

不,不起作用1)因爲SelectedItem不是一個字符串,2)即使你對它做了.ToString(),它也會返回System.Windows.Controls.ComboBoxItem。我知道我可以解析這個並獲取信息,但肯定有一個更簡單的方法? – Calanus 2009-12-08 17:39:26

7

對,答案是使用myCombo.SelectionBoxItem.ToString()

+0

確認最新silverlight作品 – 2014-03-12 17:54:01

3

對於一個複雜的對象,使用反射:

<ComboBox x:Name="MyComboBox"> 
    <ComboBox.Items> 
     <ComboBoxItem> 
      <TextBlock Text="Hello World"/> 
     </ComboBoxItem> 
    </ComboBox.Items> 
</ComboBox> 

然後,你就可以訪問選擇的項目是這樣

var itemType = cbx.SelectedItem.GetType(); 
var pi = itemType.GetProperty(cbx.DisplayMemberPath); 
var stringValue = pi.GetValue(cbx.SelectedItem, null).ToString(); 
+0

非常感謝,您的解決方案是適用於所有情況的解決方案 – sepisoad 2012-01-27 03:54:51

0

如果你有一個字符串數組的簡單組合框,你可以使用所選的字符串

(string)e.AddedItems[0]; 

假設我有一個產品列表組合,並且我想知道選定的產品名稱。所以在SelectionChanged事件我寫了下面的代碼:

private void productCombo_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) 
     { 
      string product_type=(string)e.AddedItems[0]; 
     } 
1
string txt=(comboboxID.SelectedItem as BindingClass).Text.ToString(); 

string value=(comboboxID.SelectedItem as BindingClass).Value.ToString(); 


public class BindingClass 
{ 
    public string Text 
     { 
     set; 
      get; 
     } 

    public string Value 
     { 
     set; 
      get; 
     } 
} 
+1

專用套件;將設置屬性字段爲私人。 – PhilipChrist 2013-10-11 08:12:06

1
((ComboBoxItem)comboBox1.SelectedItem).Content.ToString() 

我得到了它的工作由本聲明。