WPF: Prevent ComboBox from displaying selected item

时间:2016-10-20 18:52:45

标签: c# wpf xaml combobox

I have a ComboBoxthat I have templated to look like this:

enter image description here

Here is the XAML for this ComboBox:

<ComboBox Name="StateInclusionRules_ComboBox" 
          ItemsSource="{Binding StateInclusionRules}"
          Height="25"
          Width="155"
          Margin="0"
          Grid.Column="7">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal"
                        Margin="0">
                <Label Content="{Binding State}"
                       Margin="0,0,0,0"
                       Width="30" />
                <CheckBox IsChecked="{Binding StateTax}" 
                          Margin="20,0,0,0"/>
                <CheckBox IsChecked="{Binding StateChildSupport}" 
                          Margin="30,0,0,0"/>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Is there a way to prevent the selected item from being displayed in the ComboBox ContentPresenter (the red bordered area, i.e, the area you see when the ComboBox is closed)?

1 个答案:

答案 0 :(得分:1)

First you need 2 DataTemplates, 1 for the selected item and 1 for the drop down item.

The selected we are going to leave empty because this is your requirment. The drop down item DataTemplate will have the exact DataTemplate you wanted. When item is selected a DataTrigger will change it's template to the SelectedTemplate, like so:

  <Window.Resources>

    <DataTemplate x:Key="DropDownItemTemplate" DataType="wpfApplication1:ItemSourceModel">
        <StackPanel Orientation="Horizontal"
                    Margin="0">
            <Label Content="{Binding Value}"
                   Margin="0,0,0,0"
                   Width="30" />
            <CheckBox IsChecked="{Binding Value}" 
                      Margin="20,0,0,0"/>
            <CheckBox IsChecked="{Binding Value}" 
                      Margin="30,0,0,0"/>
        </StackPanel>
    </DataTemplate>

    <DataTemplate x:Key="SelectionBoxTemplate">

    </DataTemplate>

    <DataTemplate x:Key="ComboBoxTemplate">
        <ContentPresenter x:Name="Presenter"
               Content="{Binding}"
               ContentTemplate="{StaticResource DropDownItemTemplate}" />
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor,ComboBoxItem,1}}" Value="{x:Null}">
                <Setter TargetName="Presenter" Property="ContentTemplate" Value="{StaticResource SelectionBoxTemplate}" />
            </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>
</Window.Resources>

And set your ComboBox with the ComboBoxTemplate:

   <ComboBox Name="StateInclusionRules_ComboBox" 
      ItemsSource="{Binding YourItemSource}" ItemTemplate="{StaticResource ComboBoxTemplate}" 
      Height="25"
      Width="155"
      Margin="0"
      />