如何在单个选择时更改集合视图的颜色


<CollectionView x:Name="nList" SelectionMode="Single" VerticalScrollBarVisibility="Always" SelectionChanged="OnMakingSelection" >
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>

<SwipeView>
<SwipeView.RightItems>
<SwipeItem Text="Delete" BackgroundColor="Red" Invoked="Delete_Btn" >
</SwipeItem>
</SwipeView.RightItems>
<StackLayout BackgroundColor="AntiqueWhite">

<Label Text="{Binding UserNotes}" TextColor="Black" FontFamily="PK" FontAttributes="Bold" FontSize="33"  HorizontalOptions="Center"/>
<Label  x:Name="loclabel" Text= "{Binding Location}" FontAttributes="Bold" TextColor="Black"  HorizontalOptions="Center" />
<Button  x:Name="mapbtnnn" Text="Open in Maps" FontFamily="PF"  Clicked="Button_Clicked_Map" BackgroundColor="PowderBlue"  CornerRadius="40"   HorizontalOptions="Center"></Button>
<Image x:Name="Image" Source="{Binding Pic}" HeightRequest="90"  ></Image>
<Label Text="*END OF NOTE*" FontAttributes="Bold" TextColor="Black"  HorizontalOptions="Center"/>

</StackLayout>
</SwipeView>

</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>

想要在选中时为选中的项目添加颜色。
任何提示,
我已经尝试了很多步骤在网上,但似乎没有工作。
目前,当选择

时没有显示颜色

想要在选中时为选中的项目添加颜色。

你可以使用visual-state-manager来改变选中项目的颜色,设置切换背景色为白色,并添加VisualStateManager。如下所示:

<CollectionView x:Name="nList" SelectionMode="Single">
<CollectionView.ItemTemplate>
<DataTemplate>
<SwipeView BackgroundColor="White">
<SwipeView.RightItems>
<SwipeItem Text="Delete" BackgroundColor="Red"  >
</SwipeItem>
</SwipeView.RightItems>
<StackLayout Padding="5" Orientation="Vertical">
<Label LineBreakMode="WordWrap" Text="{Binding Name}" />
</StackLayout>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="CommonStates">
<VisualState Name="Normal" />
<VisualState Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="Yellow" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</SwipeView>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>

背后的代码:

public partial class Page1 : ContentPage
{
public Page1()
{
InitializeComponent();
nList.ItemsSource = new List<Contact>
{ 
new Contact("JP Morgan"),
new Contact("Andrew Carnegie"),
new Contact("Steve Jobs")
};
}
}
public class Contact
{
public string Name { get; set; }
public Contact(string name)
{
Name = name;
}
}

最新更新