如何更改 Xaml 中 ListView 的背景颜色?

Dav*_*het 2 xaml listview xamarin xamarin.forms

我有一个ListView, 我需要将它的原生colors(所选项目和其他项目)替换为不同的颜色。我无法找到如何做到这一点。我可以将背景颜色更改为不同的颜色(请参阅下面的代码),但我不知道如何使其表现得像普通的ListView、在选择时更改项目颜色。

这是我的代码:

<ListView x:Name="MenuItemsListView"
          SeparatorVisibility="None"
          HasUnevenRows="true"
          ItemsSource="{Binding MenuItems}">
  <ListView.Header>
    <Grid BackgroundColor="Black">
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="10"/>
      </Grid.ColumnDefinitions>
      <Grid.RowDefinitions>
        <RowDefinition Height="10"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="10"/>
      </Grid.RowDefinitions>
        <Image Grid.Column="1" Grid.Row="1" WidthRequest="50" HeightRequest="50" HorizontalOptions="StartAndExpand" Source="Assets\logo.png" />
    </Grid>
  </ListView.Header>
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell Height="100">
         <StackLayout Padding="15,10" 
                Orientation="Horizontal" 
                HorizontalOptions="FillAndExpand" 
                BackgroundColor="{StaticResource LogoBackgroundColor}">
            <Image WidthRequest="50" Source="{Binding IconSource}" />
            <Label VerticalOptions="FillAndExpand" 
                VerticalTextAlignment="Center" 
                Text="{Binding Title}" 
                FontSize="24"/>
        </StackLayout>
      </ViewCell>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>
Run Code Online (Sandbox Code Playgroud)

Arv*_*iya 5

这也可以Triggers在 xaml 中使用,但这也行得通。

要更改colorselected ViewCell,有一个简单的解决方法,无需使用自定义渲染器。使Tapped您的事件ViewCell如下

<ListView.ItemTemplate>
    <DataTemplate>
        <ViewCell Tapped="ViewCell_Tapped">            
       <StackLayout></StackLayout>
        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)

在您ContentPage的 cs 文件中,实现事件

private void ViewCell_Tapped(object sender, System.EventArgs e)
{
    if(lastCell!=null)
        lastCell.View.BackgroundColor = Color.Transparent;
    var viewCell = (ViewCell)sender;
    if (viewCell.View != null)
    {
        viewCell.View.BackgroundColor = Color.Red;
        lastCell = viewCell;
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样lastCell在你的顶部声明ContentPageViewCell lastCell;

输出截图:

在此处输入图片说明