Ido Ran
Ido Ran

Reputation: 11404

Focus on Button inside ListBoxItem without code

I have a WPF application with ListBox that display list of items. Each item has IsChecked property.

I have change the style of the ItemContainerStyle of the list box as follos:

<Style x:Key="OrgListItemStyle" TargetType="ListBoxItem">
    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    <Setter Property="VerticalContentAlignment" Value="Stretch" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBoxItem">
                <ToggleButton IsChecked="{Binding IsChecked}">
                    <ContentPresenter />
                </ToggleButton>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

The problem is that the focus, when navigating with the keyboard, is on the ListBoxItem and not the ToggleButton itself which makes it not intuitive to work with.

How ca I change the focus so it will be right on the button and not the ListBoxItem - preferable not with code.

Thank you, Ido

Upvotes: 0

Views: 720

Answers (1)

Quartermeister
Quartermeister

Reputation: 59149

You could set Focusable to false for the ListBoxItems in your Style:

<Setter Property="Focusable" Value="False"/>

Note that ListBox has some magic to remember the element that had keyboard focus that won't work if you don't allow the ListBoxItem to be selected.

If you don't want to use the features of the ListBox at all, then you may be better off using a plain ItemsControl rather than a ListBox. You would need to use a DataTemplate rather than a ControlTemplate since there is no container control:

<ItemsControl ItemsSource="{Binding Items}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ToggleButton IsChecked="{Binding IsChecked}" Content="{Binding}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Upvotes: 1

Related Questions