Displaying the selected item differently in ComboBox

前端 未结 1 1547
自闭症患者
自闭症患者 2020-12-16 08:29

I have a combo box in which I set up an ItemTemplate that looks something like this:


  
    &l         


        
相关标签:
1条回答
  • 2020-12-16 09:08

    You can do it with triggers:

    <ComboBox.ItemTemplate>
      <DataTemplate>
        <StackPanel Orientation="Horizontal">
          <TextBlock Text="{Binding Piece.NoPiece}" Width="50" x:Name="Column1" />
          <TextBlock Text="{Binding Piece.Description}" Width="170" />
          <TextBlock Text="{Binding Piece.Categorie.NomCategorie}" x:Name="Column3" />
        </StackPanel>
        <DataTemplate.Triggers>
          <!-- This trigger fires for the selected item in the drop-down list -->
          <DataTrigger Binding="{Binding 
                           RelativeSource={RelativeSource Mode=FindAncestor, 
                                                          AncestorType=ComboBoxItem},
                           Path=IsSelected}" 
            Value="True">
            <Setter TargetName="Column1" Property="Visibility" Value="Hidden" />
            <Setter TargetName="Column3" Property="Visibility" Value="Hidden" />
          </DataTrigger>
    
          <!-- This trigger fires for the selected item (ie the one that's
               visible when the popup is closed -->
          <DataTrigger Binding="{Binding 
                           RelativeSource={RelativeSource Mode=FindAncestor, 
                                                          AncestorType=ComboBoxItem}}"
                       Value="{x:Null}">
            <Setter TargetName="Column1" Property="Visibility" Value="Hidden" />
            <Setter TargetName="Column3" Property="Visibility" Value="Hidden" />
          </DataTrigger>
        </DataTemplate.Triggers>
      </DataTemplate>
    </ComboBox.ItemTemplate>
    

    EDIT

    I've updated the XAML to show how to apply the alternative formatting to the selected item when the popup is collapsed (I'm not sure what that area is called.)

    The trick is that items in the drop-down area are contained within ComboBoxItem objects in the logical tree. The RelativeSource binding looks for an object of that type as an ancestor.

    • If it finds it, it assumes that the item is in the tree (and checks whether it's selected)
    • If it's not found (null) then it assumes the item is in the combo box area rather than the popup

    This would fall apart if you, somehow, had a combo box within the item template of another combo box. I don't think I'd like to use that UI though!

    0 讨论(0)
提交回复
热议问题