简体   繁体   English

WPF MVVM ComboBox标签选择

[英]WPF MVVM ComboBox Tag Selection

I have a ComboBox that has a declared ComboBox.Items list (in other words, not dynamically bound via ItemsSource). 我有一个ComboBox,它有一个声明的ComboBox.Items列表(换句话说,不是通过ItemsSource动态绑定)。 I use the ComboBoxItem.Content for the display name and ComboBoxItem.Tag for the corresponding Id as shown below. 我使用ComboBoxItem.Content作为显示名称,使用ComboBoxItem.Tag作为相应的Id,如下所示。

How do I get the Tag of the selected item return and not the content? 如何获取所选项目的标签而不是内容? I tried SelectedItemValuePath="Tag" , but that does not work. 我尝试了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>

If you have this property in your ViewModel class: 如果您在ViewModel类中具有此属性:

 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. 当然你可以拥有int类型的属性,它也会工作。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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