Search code examples
wpfcomboboxdatabound

Disable separator selection in data bound combo box in WPF


I have a Combo Box that is databound. In this list, I need a separator. Since this is databound, I do something very similar to this post. My database returns the list, includes a '-' to mark where the separator needs to go, and the datatrigger makes this a separator.

<ComboBox Name="cbAction" Grid.Column="1" Grid.Row="0" Margin="5,2,5,2" DisplayMemberPath="Description" SelectedValuePath="Code" SelectionChanged="cbAction_SelectionChanged">
    <ComboBox.ItemContainerStyle>
        <Style TargetType="{x:Type ComboBoxItem}" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
             <Style.Triggers>
                <DataTrigger Binding="{Binding Code}" Value="-">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type ComboBoxItem}">
                                <Separator HorizontalAlignment="Stretch" IsEnabled="False"/>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

This works mostly fine, other than the issue I have here, and a minor design problem (which I will put in another question).

When using the mouse, the user can not select the separator, which is correct. But if the user uses the up/down arrow to select items, they can select the separator. This is not the default behavior, which would skip over the separator.

How can I make this separator behave similar to the way it would be if your XAML had various ComboBoxItems and a Separator item (skipping over the separator when using the up and down keys)


Solution

  • Instead of setting "Focusable" as suggested by Meleak, set "IsEnabled" to false instead in the Setter.

    <DataTrigger Binding="{Binding Code}" Value="-"> 
        <Setter Property="IsEnabled" Value="False"/>
        <Setter Property="Template"> 
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ComboBoxItem}"> 
                    <Separator HorizontalAlignment="Stretch"/> 
                </ControlTemplate> 
            </Setter.Value> 
        </Setter> 
    </DataTrigger>