问题描述
我有一个ListView,我需要将其本机颜色(所选项目和其他项目都替换为不同的颜色).我找不到解决方法.我可以将背景颜色更改为其他颜色(请参见下面的代码),但是我不知道如何使其表现为普通的ListView,从而在选择时更改项目颜色.
I have a ListView, and I need to replace its native colors (both of the selected item and other items) to different colors. I was not able to find how to do that. I can change the background color to something different (see my code below), but I don't know how to make it behave as a common ListView, changing item colors on selection.
这是我的代码:
<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
,但这也可行.
This possible using Triggers
as well in xaml but this also going to work.
要更改所选ViewCell
的color
,有一个简单的解决方法,无需使用自定义渲染器.如下所示对您的ViewCell
进行Tapped
事件
To change color
of selected ViewCell
, there is a simple work around without using custom renderer. Make Tapped
event of your ViewCell
as below
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell Tapped="ViewCell_Tapped">
<StackLayout></StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
在您的ContentPage
的CS文件中,实现事件
In your ContentPage
's cs file, implement the event
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;
输出屏幕截图:
这篇关于如何在Xaml中更改ListView的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!