欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF设置listbox控件鼠标滑过背景和字体变颜色

程序员文章站 2022-04-05 15:20:48
...


<ListBox>
    <!-- 数据 -->
    <ListBoxItem>AAAA</ListBoxItem>
    <ListBoxItem>BB</ListBoxItem>
    <ListBoxItem>CCCC</ListBoxItem>
    <!-- 设置ListBoxItem样式 -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <!-- 设置控件模板 -->
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Border Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="{TemplateBindingHorizontalContentAlignment}"
                                             VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                             TextBlock.Foreground="{TemplateBinding Foreground}"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <!-- 设置触发器 -->
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="true">
                    <Setter Property="Background" Value="Black"/>
                    <Setter Property="Foreground" Value="White"/>
                </Trigger>
                <Trigger Property="IsMouseOver" Value="true">
                    <Setter Property="Background" Value="LightGreen"/>
                    <Setter Property="Foreground" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>