我在这个论坛上看到了之前询问的项目的回复:如何更改 CollectionView 中所选项目的背景颜色。当我们在列表中选择一个项目时,它可以正常工作(所选项目在选择时采用背景颜色,在本例中为 LightSkyBlue)。但是,当通过事件选择该项目时,背景颜色不会修改。旧的所选项目保留背景颜色(LightSkyBlue),新的所选项目采用默认背景颜色(lightGray)
这是 XAML 摘录:
<Button x:Name="btnCollection" Text="ActionCollections" Clicked="btnCollection_Clicked" WidthRequest="200"/>
<CollectionView x:Name="MaCollection" ItemsSource= "{Binding ItemsList}"
SelectionMode="Single"
SelectedItem="{Binding MySelected}"
MaximumHeightRequest="100" WidthRequest="300" >
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding .}" />
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="CommonStates">
<VisualState Name="Normal"></VisualState>
<VisualState Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="LightSkyBlue"></Setter>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
这里是.cs
private string _mySelected;
public string MySelected
{
get { return _mySelected; }
set
{
if (_mySelected != value)
{
_mySelected = value;
OnPropertyChanged();
}
}
}
public ObservableCollection<String> ItemsList { get; } = new ObservableCollection<String>();
private void btnCollection_Clicked(object sender, EventArgs e)
{
MySelected = "maliste5"; // an item in the list
}
使用 OnItemSelected 事件:
void OnItemSelected(object sender, SelectedItemChangedEventArgs args){
if (sender != null)
(sender as ListView).SelectedItem.BackgroundColor = Color.LightSkyBlue;
}