简体   繁体   中英

WPF MVVM ComboBox Tag Selection

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

How do I get the Tag of the selected item return and not the content? I tried SelectedItemValuePath="Tag" , but that 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>

If you have this property in your ViewModel class:

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

Of course you can have property of type int and it will be working 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>

给组合框一个名字“x:Name =”abcComboBox“然后在代码端字符串标签=(abcComboBox.SelectedItem as ComboBoxItem).Tag.ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM