【问题标题】:Focus on Button inside ListBoxItem without code无需代码即可专注于 ListBoxItem 内的 Button
【发布时间】:2023-03-20 20:15:01
【问题描述】:

我有一个带有显示项目列表的 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 - 最好不要使用代码。

谢谢你, 伊多

【问题讨论】:

    标签: wpf


    【解决方案1】:

    您可以将样式中的 ListBoxItems 的 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>
    

    【讨论】:

    • 谢谢,我真的很紧张 - ItemsControl 是解决这个问题的正确方法。
    猜你喜欢
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 2018-09-20
    相关资源
    最近更新 更多