【问题标题】:WPF MVVM ComboBox Tag SelectionWPF MVVM 组合框标签选择
【发布时间】:2012-11-03 03:12:33
【问题描述】:

我有一个 ComboBox,它有一个声明的 ComboBox.Items 列表(换句话说,不是通过 ItemsSource 动态绑定的)。我使用 ComboBoxItem.Content 作为显示名称,使用 ComboBoxItem.Tag 作为对应的 Id,如下所示。

如何获取所选项目的标签而不是内容?我试过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>

【问题讨论】:

    标签: c# wpf mvvm combobox


    【解决方案1】:

    给组合框起一个名字" x:Name = "abcComboBox" 然后在代码端 string tag = (abcComboBox.SelectedItem as ComboBoxItem).Tag.ToString();

    【讨论】:

      【解决方案2】:

      如果你的 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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-19
        • 2012-12-16
        • 1970-01-01
        • 2014-03-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多