listview - 如何更改 Xaml 中 ListView 项目的背景颜色?

标签 listview 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>

最佳答案

这也可以在 xaml 中使用 Triggers,但这也会起作用。

要更改所选 ViewCellcolor,有一个简单的解决方法,无需使用自定义渲染器。如下所示制作 ViewCellTapped 事件

<ListView.ItemTemplate>
    <DataTemplate>
        <ViewCell Tapped="ViewCell_Tapped">            
       <StackLayout></StackLayout>
        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate>

在你的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;
    }
}

像这样在 ContentPage 的顶部声明 lastCell ViewCell lastCell;

输出截图:

enter image description here

关于listview - 如何更改 Xaml 中 ListView 项目的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53595003/

相关文章:

django - annotate() - 对另一列进行过滤的列的 Sum()

java - 从 Android 中的可检查 ListView 中删除所有选定的项目

java - 我在 Android 中遇到了 null 异常,我找不到位置,最糟糕的是 - 为什么?

c# - Xamarin Forms 从 sqlite 数据库中删除

c# - 更改链接到 ListView 中所选项目的文本框中的值后,数据库中的表未更新

android - ListView 中的 ArrayIndexOutOfBounds 异常

php - Xamarin.Forms Android 和 iOS 与 Sqlite 是否可以同步到 MySql?

c# - 将 JSON 反序列化到 SQLite 数据库中

xaml - Xamarin.Forms:单击 ListView 中的项目时如何显示模式?

c# - 如何从 tabbarController.ViewControllerS 选定事件中删除/垃圾收集附加方法?