2012-11-14 183 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() ;