2012-11-14 141 views
7

我有一個組合框具有一個聲明ComboBox.Items列表(換句話說,不通過ItemsSource動態綁定)。我使用ComboBoxItem.Content作爲顯示名稱,ComboBoxItem.Tag作爲相應的Id,如下所示。WPF MVVM組合框標籤選擇

如何獲取所選項目的標籤而不是內容?我試過SelectedItemValuePath="Tag",但那不行。

<ComboBox Visibility="{Binding Path=ShowOutpatientFields, Converter= 
     {StaticResource 
      boolTovisConverter}}" Grid.Row="5" Grid.Column="2" Margin="0,2,0,2" 
     Text="{Binding Path=NewCase.ServiceType, ValidatesOnDataErrors=true, 
     NotifyOnValidationError=true}" SelectedValuePath="Tag"> 
      <ComboBox.Items> 
      <ComboBoxItem Content="Hospice" Tag="33" /> 
      <ComboBoxItem Content="Hospital Outpatient" Tag="36" /> 
      <ComboBoxItem Content="Hospital Inpatient Extension" Tag="128" /> 
      <ComboBoxItem Content="Maternity" Tag="52" /> 
      </ComboBox.Items> 
    </ComboBox> 

回答

8

如果你在你的ViewModel類此屬性:

private string _serviceType; 
public string ServiceType 
{ 
    get { return _serviceType; } 
    set { _serviceType = value; } 
} 

當然,你可以有一個int類型的屬性,它會被工作壓力太大。

嘗試此結合:

<ComboBox VerticalAlignment="Center" Margin="0,2,0,2" 
       SelectedValue="{Binding ServiceType}" 
       SelectedValuePath="Tag"> 
      <ComboBox.Items> 
       <ComboBoxItem Content="Hospice" Tag="33" /> 
       <ComboBoxItem Content="Hospital Outpatient" Tag="36" /> 
       <ComboBoxItem Content="Hospital Inpatient Extension" Tag="128" /> 
       <ComboBoxItem Content="Maternity" Tag="52" /> 
      </ComboBox.Items> 
     </ComboBox> 
+1

完美!謝謝! – NickV

+0

不客氣:) – kmatyaszek

0

給組合框的名稱「×:名稱= 」abcComboBox「,然後在代碼側 字符串標記=(abcComboBox.SelectedItem如ComboBoxItem).Tag.ToString() ;