2013-10-18 103 views
11

我如何從下面的示例中獲取選定值(例如Option1)作爲string。我在Google上嘗試了大量建議,但無法獲取字符串。獲取wpf組合框選定的值

XAML:

<ComboBox x:Name="selectOption" Text="Select Option" 
       SelectionChanged="selectOption_SelectionChanged" 
       SelectedValue="{Binding VMselectedOption, Mode=TwoWay}" > 
    <ComboBoxItem Name="cbb1">Option1</ComboBoxItem> 
    <ComboBoxItem Name="cbb2">Option2</ComboBoxItem> 
    <ComboBoxItem Name="cbb3">Option3</ComboBoxItem> 
</ComboBox> 

代碼隱藏:

private void selectOption_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    var selectedValue = selectOption.SelectedValue; 
} 

//elsewhere in code 
var test = viewModel.VMselectedOption; 

兩個了selectedValue和測試返回字符串 「System.Windows.Controls.ComboBoxItem:選項」,而不是「選項1

這應該很簡單,但我不能得到這個工作或看看有什麼不對?

回答

12

您不應手動插入組合框項目。使用ItemsSource進行設置。

基本上你應該創建的選項(或代表選擇的對象)的列表,並將它們設置爲ItemsSource,這樣一來你的SelectedItem將完全被選擇的選項,而不是自動創建包裝ComboboxItem

+2

你是我見過的唯一明智的答案。 –

+0

它使用ItemsSource完美工作,謝謝。 – user3357963

+0

@ooo:很高興它有幫助。考慮到內容和演示的分離,使用'ItemsSource'是一個不錯的選擇。 – Vlad

7

更新您的代碼以獲取ComboboxItem的內容。

var selectedValue = ((ComboBoxItem)selectOption.SelectedItem).Content.ToString(); 
8
string Value=""; 
if(myComboBox.SelectedIndex>=0) 
    Value=((ComboBoxItem)myComboBox.SelectedItem).Content.ToString(); 
+0

最好檢查:if(((ComboBoxItem)myComboBox.SelectedItem).Content!= null)。因爲如果對某些元素使用IsSelected =「True」,則初始化後內容將爲空。 – Sasha

18

您應該設置SelectedValuePath = 「內容」。

<ComboBox x:Name="selectOption" Text="Select Option" 
       SelectionChanged="selectOption_SelectionChanged" 
       SelectedValue="{Binding VMselectedOption, Mode=TwoWay}" 
       SelectedValuePath="Content"> 
    <ComboBoxItem Name="cbb1">Option1</ComboBoxItem> 
    <ComboBoxItem Name="cbb2">Option2</ComboBoxItem> 
    <ComboBoxItem Name="cbb3">Option3</ComboBoxItem> 
</ComboBox>