无需代码即可专注于ListBoxItem内的Button

时间:2010-08-01 16:43:53

标签: wpf

我有一个带有ListBox的WPF应用程序,它显示了项目列表。 每个项目都有IsChecked属性。

我已将列表框的ItemContainerStyle的样式更改为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>

问题在于,当使用键盘导航时,焦点位于ListBoxItem上,而不是ToggleButton本身,这使得使用起来不直观。

如何更改焦点,使其在按钮上而不是ListBoxItem上 - 最好不要使用代码。

谢谢你, IDO

1 个答案:

答案 0 :(得分:1)

您可以为样式中的ListBoxItem设置Focusable为false:

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

请注意,如果不允许选择ListBoxItem,ListBox有一些魔法可以记住具有键盘焦点的元素无效。

如果您根本不想使用ListBox的功能,那么最好使用普通的ItemsControl而不是ListBox。由于没有容器控件,您需要使用DataTemplate而不是ControlTemplate:

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