WPF 中 通过点击ListBox中的元素自动选中一整项

由于WPF中,经常有个问题点击Listbox中的里面的元素经常不会选中某项,选中的项也不会变颜色,这个其实可以通过修改样式去实现。

        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="SnapsToDevicePixels"
                    Value="True" />
            <Setter Property="FocusVisualStyle"
                    Value="{x:Null}" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Border Name="Border"
                                Padding="1 1 1 1"
                                Background="Transparent"
                                SnapsToDevicePixels="True"
                                CornerRadius="20">
                            <ContentPresenter />
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsSelected"
                                     Value="True">
                                <Setter TargetName="Border"
                                        Property="Background"
                                        Value="#D84E20" />
                                <Setter Property="Foreground"
                                        Value="White" />
                            </Trigger>
                            <Trigger Property="IsEnabled"
                                     Value="false">
                                <Setter Property="Foreground"
                                        Value="White" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsKeyboardFocusWithin"
                         Value="true">
                    <Setter Property="IsSelected"
                            Value="true" />
                </Trigger>

                <EventTrigger RoutedEvent="PreviewGotKeyboardFocus">
                    <BeginStoryboard>
                        <Storyboard>
                            <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="(ListBoxItem.IsSelected)">
                                <DiscreteBooleanKeyFrame KeyTime="0"
                                                         Value="True" />
                            </BooleanAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Style.Triggers>
        </Style>

留个笔记作为参考,方便以后使用。感谢您的浏览。

posted @ 2021-04-22 09:13  Lexan  阅读(614)  评论(0编辑  收藏  举报