You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET MAUI的UWP平台设置ListView选中项背景色

UWP ListView选中项高亮颜色自定义方案

方法一:自定义ListViewItem的ItemContainerStyle

直接在ListView的ItemContainerStyle中修改选中状态的视觉效果,是最直接的实现方式:

<ListView>
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListViewItem">
                        <Grid x:Name="RootGrid">
                            <!-- 渲染列表项内容 -->
                            <ContentPresenter Content="{TemplateBinding Content}"
                                              ContentTemplate="{TemplateBinding ContentTemplate}"
                                              Padding="{TemplateBinding Padding}"/>
                            <!-- 配置选中状态的视觉效果 -->
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="SelectionStates">
                                    <VisualState x:Name="Unselected"/>
                                    <VisualState x:Name="Selected">
                                        <VisualState.Setters>
                                            <Setter Target="RootGrid.Background" Value="#FF0078D7"/>
                                            <!-- 替换为你需要的高亮颜色值 -->
                                        </VisualState.Setters>
                                    </VisualState>
                                    <VisualState x:Name="SelectedUnfocused">
                                        <VisualState.Setters>
                                            <Setter Target="RootGrid.Background" Value="#FF0078D7"/>
                                        </VisualState.Setters>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListView.ItemContainerStyle>
    <!-- 列表项内容 -->
</ListView>

方法二:覆盖系统资源(全局生效)

如果希望所有ListView的选中项统一使用自定义颜色,可在App.xaml中覆盖对应的系统主题资源:

<Application.Resources>
    <!-- 选中且聚焦时的背景色 -->
    <SolidColorBrush x:Key="ListViewItemSelectedBackgroundThemeBrush" Color="#FF0078D7"/>
    <!-- 选中但失焦时的背景色 -->
    <SolidColorBrush x:Key="ListViewItemSelectedUnfocusedBackgroundThemeBrush" Color="#FF0078D7"/>
</Application.Resources>

配置后无需修改每个ListView的样式,全局范围内的ListView选中项都会自动应用你设置的颜色。

补充说明

  • 颜色值可替换为任意十六进制颜色代码或预定义颜色名称
  • 若需修改选中状态下的文字颜色,可额外覆盖ListViewItemSelectedForegroundThemeBrush资源

内容的提问来源于stack exchange,提问作者sowndarrajan vijayaragavan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 08:44:59