WPF MVVM ComboBox Tag Selection

I have a ComboBox that has a declared list of ComboBox.Items (in other words, it is not dynamically linked via ItemsSource). I use ComboBoxItem.Content for the display name and ComboBoxItem.Tag for the corresponding identifier, as shown below.

How to get the tag of the selected item, not the content? I tried SelectedItemValuePath="Tag" , but this does not work.

  <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> 
+7
source share
2 answers

If you have this property in your ViewModel class:

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

Of course, you may have a property of type int, and it will work too.

Try this binding:

 <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> 
+8
source

Give the combobox the name "x: Name =" abcComboBox "and then on the code side string tag = (abcComboBox.SelectedItem as ComboBoxItem) .Tag.ToString ();

0
source

All Articles