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

3
我有一个ListView,我需要将其本地颜色(选定项和其他项的颜色)替换为不同的颜色。我无法找到如何做到这一点。我可以将背景颜色更改为不同的颜色(请参见下面的代码),但我不知道如何使它像普通的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,还是需要代码后台? - R15
@CGPA6.4 我更喜欢 XAML,但如果我找不到 XAML 的解决方案,我会考虑使用代码后台。谢谢。 - David Shochet
2个回答

8

在XAML中,也可以使用触发器实现这一点,但本方法同样适用。

要更改所选ViewCell颜色,有一个简单的解决方法,不需要使用自定义呈现器。将您的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


奇怪的是,尽管执行到了viewCell.View.BackgroundColor = Color.Red;这一行,但颜色并没有改变。 - David Shochet
这在安卓上对我没用(没有尝试iOS)。这个答案有效:https://stackoverflow.com/a/67830897/1214875 - DrCJones
我已确认这在Android上可以运行,在当前版本的XForms上。 - ToolmakerSteve

0

在XAML中无法做到这样的事情。如果建议的解决方案不起作用,您可以在ViewCell内放置一个Grid并更改其颜色,这是您可以接近XAML的最佳方法。但它相当低效。

您的问题的唯一真正解决方案在本地端。在Android上,这相当简单,您可以编辑styles.xml来实现。在其他平台上,您需要编写自定义渲染器。


谢谢。我对Xamarin非常陌生。顺便说一下,我使用UWP。 - David Shochet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接