.NET MAUI CollectionView选中项无高亮效果求助(Windows平台)
CollectionView选中项无高亮问题(Windows平台)
问题根源
你错误地将VisualStateManager应用在了CollectionView控件本身上,而选中状态的视觉反馈应该作用在每个列表项的根容器(即ItemTemplate内的Grid)上。此外,你用Frame覆盖了整个列表项区域,Frame的不透明背景会完全挡住根容器的背景色变化,导致高亮无法显示。
解决步骤
- 将
VisualStateManager移至ItemTemplate的根Grid内部,让选中状态作用于单个列表项。 - 调整
Frame的背景透明度,使根容器的选中背景能透出来;或直接在选中状态下修改Frame的样式。
修改后的代码示例
<CollectionView x:Name="CollectionOfItems" ItemsSource="{Binding Items}" Header="{Binding .}" Grid.Row="2" Grid.Column="0" BackgroundColor="Grey" Margin="20,0,0,0" WidthRequest="1750" HorizontalOptions="Start" VerticalOptions="Start" SelectionMode="Single" SelectedItem="{Binding SelectedItem}"> <CollectionView.ItemTemplate> <DataTemplate x:DataType="m:Item"> <Grid Margin="0" RowDefinitions="*" ColumnDefinitions="*,*,*,*,*"> <!-- 将VisualStateManager移至列表项的根Grid中 --> <VisualStateManager.VisualStateGroups> <VisualStateGroup Name="CommonStates"> <VisualState Name="Normal"/> <VisualState Name="Selected"> <VisualState.Setters> <Setter Property="BackgroundColor" Value="LightBlue"/> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <!-- 将Frame背景改为半透明,让Grid的选中背景透出 --> <Frame x:Name="SerialNumberFrame" CornerRadius="0" BorderColor="Black" Grid.Column="0" BackgroundColor="#CCFFFFFF"> <Label Text="{Binding SerialNumber}" HorizontalOptions="Start"> </Label> </Frame> <Frame CornerRadius="0" BorderColor="Black" BackgroundColor="#CCLightGrey" Grid.Column="1"> <Label Text="{Binding ItemType.Text}" HorizontalOptions="Start"> </Label> </Frame> <Frame CornerRadius="0" BorderColor="Black" BackgroundColor="#CCFFFFFF" Grid.Column="2"> <Label Text="{Binding HasAllComponents.Text}" HorizontalOptions="Start"> </Label> </Frame> <Frame CornerRadius="0" BorderColor="Black" BackgroundColor="#CCLightGrey" Grid.Column="3"> <Label Text="{Binding MissionCapable.Text}" HorizontalOptions="Start"> </Label> </Frame> <Frame CornerRadius="0" BorderColor="Black" BackgroundColor="#CCFFFFFF" Grid.Column="4"> <Label Text="{Binding CheckedOut.Text}" HorizontalOptions="Start"> </Label> </Frame> </Grid> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView>
替代方案(无需修改透明度)
如果不想改变Frame的透明度,可以在选中状态下直接修改所有Frame的背景色,示例如下:
<VisualState Name="Selected"> <VisualState.Setters> <Setter TargetName="SerialNumberFrame" Property="BackgroundColor" Value="LightBlue"/> <Setter TargetName="ItemTypeFrame" Property="BackgroundColor" Value="LightBlue"/> <!-- 给其他Frame添加x:Name后,依次设置选中背景 --> </VisualState.Setters> </VisualState>
内容的提问来源于stack exchange,提问作者TrollKilla
相关产品推荐
相关产品推荐

